ArgumentException:已添加具有相同键的项目
每当我提交表单时,我都会收到此错误,而且操作方法也不会被调用,因为:
ArgumentException:已添加具有相同键的项目。
以及异常详细信息:
[ArgumentException:带有 已添加相同的密钥。]
System.ThrowHelper.ThrowArgumentException(ExceptionResource 资源)+52
System.Collections.Generic.Dictionary`2.Insert(TKey 键、TValue 值、布尔相加) +9382923 System.Linq.Enumerable.ToDictionary(IEnumerable`1 源,Func`2 keySelector,Func`2 元素选择器,IEqualityComparer`1 比较器)+252
System.Linq.Enumerable.ToDictionary(IEnumerable`1 源代码,Func`2 keySelector, IEqualityComparer`1 比较器) +91
System.Web.Mvc.ModelBindingContext.get_PropertyMetadata() +228 System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext 控制器上下文、模型绑定上下文 绑定上下文、属性描述符 属性描述符)+392
System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext 控制器上下文、模型绑定上下文 绑定上下文)+147
System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext 控制器上下文、模型绑定上下文 绑定上下文,对象模型)+98
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext 控制器上下文、模型绑定上下文 绑定上下文)+2504
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext 控制器上下文、模型绑定上下文 绑定上下文)+548
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext 控制器上下文、参数描述符 参数描述符)+473
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext 控制器上下文、动作描述符 动作描述符)+181
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext 控制器上下文,字符串操作名称) +830 System.Web.Mvc.Controller.ExecuteCore() +136 System.Web.Mvc.ControllerBase.Execute(RequestContext 请求上下文)+111
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext 请求上下文)+39
System.Web.Mvc.<>c__DisplayClass8.b__4() +65 System.Web.Mvc.Async.<>c__DisplayClass1.b__0() +44 System.Web.Mvc.Async。<>c__DisplayClass8`1.b__7(IAsyncResult _) +42 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,对象标签)+54
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,对象标签)+40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult 异步结果)+52
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult 结果)+38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8836913 System.Web.HttpApplication.ExecuteStep(IExecutionStep 步骤,布尔值&同步完成) +184
ViewPage
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/XYZ.Master"
Inherits="System.Web.Mvc.ViewPage<XYZ.Models.Admin.AdminSegmentCommissionsModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) {%>
<div class="box3">
<div class="userinfo">
<h3>Admin Segment Commissions</h3>
</div>
<div class="buttons-panel">
<ul>
<li>
<input type="submit" value="Save" class="save" />
</li>
<li>
<%:Html.ActionLink("Cancel", "Index", new { controller = "AdminSegmentCommissions" }, new { @class = "cancel" })%>
<%--<input type="button" value="Cancel" class="cancel" onclick="document.location.href='/AirlineLedgerTransactionReceiver/Index'" />--%>
</li>
</ul>
</div>
</div>
<div class="row-1">
<div class="form-box1 round-corner">
<div class="form-box1-row">
<div class="form-box1-row-content float-left">
<div>
<label>
<%: Html.LabelFor(model => model.FromSegmentNumber) %></label>
<%: Html.TextBoxFor(model => model.FromSegmentNumber) %>
<%: Html.ValidationMessageFor(model => model.FromSegmentNumber) %>
</div>
</div>
</div>
</div>
</div>
<%} %>
I get this error whenever I submit the form also the action method is not being called because of this:
ArgumentException: An item with the same key has already been added.
And the exception details:
[ArgumentException: An item with the
same key has already been added.]
System.ThrowHelper.ThrowArgumentException(ExceptionResource
resource) +52
System.Collections.Generic.Dictionary`2.Insert(TKey
key, TValue value, Boolean add)
+9382923 System.Linq.Enumerable.ToDictionary(IEnumerable`1
source, Func`2 keySelector, Func`2
elementSelector, IEqualityComparer`1
comparer) +252
System.Linq.Enumerable.ToDictionary(IEnumerable`1
source, Func`2 keySelector,
IEqualityComparer`1 comparer) +91
System.Web.Mvc.ModelBindingContext.get_PropertyMetadata()
+228 System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext
controllerContext, ModelBindingContext
bindingContext, PropertyDescriptor
propertyDescriptor) +392
System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext
controllerContext, ModelBindingContext
bindingContext) +147
System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext
controllerContext, ModelBindingContext
bindingContext, Object model) +98
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext
controllerContext, ModelBindingContext
bindingContext) +2504
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext
controllerContext, ModelBindingContext
bindingContext) +548
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext
controllerContext, ParameterDescriptor
parameterDescriptor) +473
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext
controllerContext, ActionDescriptor
actionDescriptor) +181
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName)
+830 System.Web.Mvc.Controller.ExecuteCore()
+136 System.Web.Mvc.ControllerBase.Execute(RequestContext
requestContext) +111
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext
requestContext) +39
System.Web.Mvc.<>c__DisplayClass8.b__4()
+65 System.Web.Mvc.Async.<>c__DisplayClass1.b__0()
+44 System.Web.Mvc.Async.<>c__DisplayClass8`1.b__7(IAsyncResult
_) +42 System.Web.Mvc.Async.WrappedAsyncResult`1.End()
+141 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult
asyncResult, Object tag) +54
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult
asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult
asyncResult) +52
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult
result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+8836913 System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously)
+184
ViewPage
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/XYZ.Master"
Inherits="System.Web.Mvc.ViewPage<XYZ.Models.Admin.AdminSegmentCommissionsModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) {%>
<div class="box3">
<div class="userinfo">
<h3>Admin Segment Commissions</h3>
</div>
<div class="buttons-panel">
<ul>
<li>
<input type="submit" value="Save" class="save" />
</li>
<li>
<%:Html.ActionLink("Cancel", "Index", new { controller = "AdminSegmentCommissions" }, new { @class = "cancel" })%>
<%--<input type="button" value="Cancel" class="cancel" onclick="document.location.href='/AirlineLedgerTransactionReceiver/Index'" />--%>
</li>
</ul>
</div>
</div>
<div class="row-1">
<div class="form-box1 round-corner">
<div class="form-box1-row">
<div class="form-box1-row-content float-left">
<div>
<label>
<%: Html.LabelFor(model => model.FromSegmentNumber) %></label>
<%: Html.TextBoxFor(model => model.FromSegmentNumber) %>
<%: Html.ValidationMessageFor(model => model.FromSegmentNumber) %>
</div>
</div>
</div>
</div>
</div>
<%} %>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="CssContent" runat="server">
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="JSContent" runat="server">
</asp:Content>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
我遇到了类似的异常。检查所有列的标题名称(来自数据库中的选择查询)是否与模型类中的属性名称完全匹配。
I faced similar exception. Check if all columns has header names( from select query in database) with exactly matching property names in model class.
我在 DBContext 上遇到了这个问题。
当我尝试在程序包管理器控制台中运行更新数据库以添加迁移时出现错误:
public virtual IDbSet Status { get;放;问题
在于类型和名称相同。
我将其更改为:
public virtual IDbSet Statuses { get;放; }
I had this issue on the DBContext.
Got the error when I tried run an update-database in Package Manager console to add a migration:
public virtual IDbSet Status { get; set; }
The problem was that the type and the name were the same.
I changed it to:
public virtual IDbSet Statuses { get; set; }
我遇到了这个确切的错误,不是因为属性名称,而是因为有重复的自定义属性值。
I had this exact error, not because of property names, but for having duplicate custom attribute values.
就我而言,这是因为我在 for 中使用了 JoinAlias。
In my case it was because I used JoinAlias within a for.
当您使用 context.Entity.FromSqlRaw() 时,SQL 查询列名称必须等于 C# 类属性名称。
When you use context.Entity.FromSqlRaw() , SQL query column names must equal to C# class property names.
当我返回不同 API 的响应时,我遇到了同样的问题。重复
200 OK
。我的解决办法是简单地评论它。I had the same issue when returning responses to different APIs.
200 OK
was repeated. My fix was to simply comment it.当模型包含一个值为 0 的引用属性并用属性 [Required] 修饰并尝试将新记录添加到数据库时,问题就出现了:
在尝试添加到数据库时,EntityFramework 尝试增加它。对于模型,EF 将 Id 属性递增到最后存储的类模型之后。当其他记录已存储时,SomeOtherClassModelId EF 将从 0 更改为 1,然后出现异常。
The problem reared it's head when the model contained a reference property with a value of zero and is decorated with attribute [Required] and attempt to add a new record to the DB:
Upon trying to add to the DB, EntityFramework tries to increment it. For the model, EF increments Id property one past the last class model stored. With other records already stored, the SomeOtherClassModelId EF changes zero to 1 then comes the exception.
对于任何在 MAUI 上对此感到困惑的人来说,对我们来说,这是一个由于配置错误的错误响应而每秒被调用的弹出窗口。该弹出窗口并未在主(UI)线程上调用,因此有大量未显示的弹出窗口不断堆积,直到出错。
For anyone bewildered by this on MAUI, for us it was a popup that was being called every second due to a misconfigured error response. The popup was not being called on the Main (UI) thread, so there were a ton of popups that weren't being shown that just kept piling up until it errored out.
就我而言,我有 SELECT * FROM SomeTable INNER JOIN AnotherTable,其中两个表的 PK 具有相同的名称。这在 SSMS 中运行良好,但由于某些原因,在我的 C# 代码中,通过 FromSql() 调用此 SQL 导致了 OP 的异常。
修复方法是从
JOIN
结果中SELECT
特定列,而不是*
。In my case, I had
SELECT * FROM SomeTable INNER JOIN AnotherTable
, where the two tables' PKs had identical names. This ran fine in SSMS, but for some reason in my C# code, calling this SQL via FromSql() resulted in OP's exception.The fix was to
SELECT
specific columns from the result of theJOIN
, rather than*
.我在执行 Stord 过程时遇到了同样的问题,并且返回了两列同名的列。当在模型类中映射该列时,会发生冲突。要解决该问题,请始终对返回的列使用唯一的名称。
I had the same issue when executing a Stord Procedure and It has been returned two columns with the same name. When mapping that column inside the model class there is a conflict. To solve that issue always use unique names for returned columns.
我遇到了同样的问题,我正在
foreach
循环遍历我的对象并将结果添加到Dictionary
中,并且我有一个“重复的密钥”数据库item.x
有重复值I had the same issue , i was
foreach
looping over my object and adding the result into aDictionary<string, string>
and i had a `Duplicate in the key from the databaseitem.x
had a duplicate value我找到了答案。这是因为变量。就像 int a 和 string a 一样。有两个同名的变量。
I found the answer.It was because of the variables. Like int a and string a. there were two variables with the same name.
就我而言,只要编译代码,它就可以正常运行。但是,像示例代码一样,调用具有字典的静态类的静态字段之一会引发异常。
示例代码
说明
ADict 添加了两次“test”键。因此,当您调用静态类时,它会抛出异常。
In my case, simply when you compile the code, it runs just fine. But calling one of a static field of a static class that has a dictionary like sample code has, throws the exception.
Sample code
Explanation
ADict has "test" key added twice. So, when you call the static class, it throws the exception.
2021 年 - 三月
演示 dotnetfiddle
在我的例子中,字典中的
key
是重复的。2021 - March
Demo on dotnetfiddle
In my case, the
key
in the dictionary is duplicated.这是我为了找出被添加两次的密钥所做的事情。我从 http://referencesource.microsoft.com/DotNetReferenceSource.zip 下载源代码并进行设置VS调试框架源码。在 VS 中打开 Dictionary.cs 运行项目,页面加载后,在
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
行添加调试,并能够看到“key”值。我意识到在 JSON 中变量的一个字母是大写的,但在我的模型中它是小写的。我修复了模型,现在相同的代码可以工作。Here is what I did to find out the key that was being added twice. I downloaded the source code from http://referencesource.microsoft.com/DotNetReferenceSource.zip and setup VS to debug framework source. Opened up Dictionary.cs in VS ran the project, once page loads, added a debug at the line
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
and was able to see the 'key' value. I realized that in the JSON one letter of a variable was in upper case but in my model it was lowercase. I fixed the model and now the same code works.我在 MVC 5 和 Visual Studio Express 2013 中遇到了这个问题。我有两个带有
IndexAttribute
的属性,如下所示。注释掉其中之一并重新编译会导致使用视图搭建 MVC 5 控制器,并成功使用实体框架。神秘的是,当我取消注释该属性、重新编译并再次尝试时,脚手架运行得很好。也许底层实体数据模型或“某些东西”被缓存/损坏,删除并重新添加
IndexAttribute
只是触发了该“某些东西”的重建。I hit this in MVC 5 and Visual Studio Express 2013. I had two properties with an
IndexAttribute
like below. Commenting out one of them and recompiling resulted in scaffolding the MVC 5 controller with views, using Entity Framework succeeding. Mysteriously, when I uncommented the attribute, recompiled, and tried again, the scaffolder ran just fine.Perhaps the underlying entity data model or "something" was cached/corrupted, and removing and re-adding the
IndexAttribute
simply triggered a rebuild of that "something".在 MVC 5 中,我发现暂时注释掉对实体框架模型的引用,并在搭建脚手架时重新编译项目方会出现此错误。完成脚手架后,我取消注释代码。
In MVC 5 I found that temporarily commenting out references to an Entity Framework model, and recompiling the project side stepped this error when scaffolding. Once I finish scaffolding I uncomment the code.
我想添加一个我在这里没有看到的答案。它与已接受的答案非常相关,但是,我的模型上没有重复的属性,这是我的 Javascript 的问题。
我正在做一些 Ajax 保存,重建模型以发送回服务器。当我第一次初始化页面时,我将原始模型设置为一个变量:
我的
result.Data
有一个属性:result.Data.Items
所以,一段时间后,我通过 Ajax 做一些事情并想保存。该过程的一部分是从某个侧面进程获取一个数组并将其设置为我的 currentModel.Items 属性并将 currentModel 发送到服务器。
然而,在我的 Javascript 中,我这样做了:
我没有注意到它,但在 Visual Studio 中,它会自动小写 Javascript 属性的第一个字母(它也可能是 ReSharper 的东西)。然后,当我尝试保存时,我收到了 OP 发布的确切错误,因为 currentModel 现在具有
currentModel.items
和currentModel.Items
从“items”到“Items”的简单更改“解决了问题。
I would like to add an answer that I do not see here. It is very related to the accepted answer, however, I did not have duplicated properties on my model, it was an issue with my Javascript.
I was doing some Ajax save where I was rebuilding the model to send back to the server. When I had first initialized the page I set my original model to a variable:
My
result.Data
has a property:result.Data.Items
So, some time later, I do some things and want to save, via Ajax. Part of the process is to grab an array from some side process and set it to my
currentModel.Items
property and sendcurrentModel
to the server.In my Javascript, however, I did this, instead:
I didn't catch it, but in Visual Studio, it will auto lower case the first letter for Javascript properties (it could be a ReSharper thing too). Then, I got the exact error posted by OP when I tried to save because currentModel now has
currentModel.items
ANDcurrentModel.Items
A simple change from "items" to "Items" fixed the problem.
我的问题是我有一个 @Url.Action 并且我已经为同一属性发送了两次值
My problem was that I had a @Url.Action and I had sent through a value for the same property twice
我有同样的问题。从 MVC 3 迁移到 MVC 5 后,我发现了这
一点。我有自定义编辑器模板,并且之前必须像这样使用它:
为了解决问题,我必须删除传递的 ViewData 对象。所以最后我有:
希望有帮助。
I had same issue. It appeard to me after migrating to MVC 5 from MVC 3.
I had custom editor template and had to use it like this before:
To resolve issue I had to remove passing
ViewData
object. So at the end I had:Hope it helps.
我也有同样的错误。在我已经认为我的精神崩溃了之后,因为我已经重命名了几乎所有模型属性,所以解决方案是删除所有 Syncfusion 控件上的一个引用,并添加对此控件的各个控件的引用。 (来自努吉特)
I have had the same error. And after I have already thought my mind is broken, because I had rename almost all my models properties the solution was delete one reference on All Syncfusion Controls and add references to the individual controls of this controls. (From Nuget)
就我而言,问题的根源是客户端 json 中重复的属性名称,仅区分大小写。
In my case the root of the problem was duplicate property name in the client json which only differed by case sensitivity.
遇到此错误的另一种方法是来自具有未命名列的数据集。当数据集序列化为 JSON 时,会抛出该错误。
此语句将导致错误:
添加列名将防止错误:
Another way to encounter this error is from a dataset with unnamed columns. The error is thrown when the dataset is serialized into JSON.
This statement will result in error:
Adding column names will prevent the error:
我有同样的错误,但 b/c 的原因不同。使用实体框架。在分享我的代码和解决方案之前,我还需要在此处添加一件事,我在控制器方法上有一个断点,但它并没有在那里中断,只是抛出异常 500 内部服务器错误。
我通过ajax(http post)将数据从视图发布到控制器。我期望作为参数的模型是一个类。它是与其他一些类一起继承的。
并在视图中
简单地从PurchaseOrder类中删除重复的字段,它就像一个魅力。
I have had the same error but b/c of diff reason. Using Entity framework. One more thing I need to add here before I share my code and solution, I had a break point on controller method but it was not breaking there, just throwing exception 500 internal server error.
I was posting data from view to controller through ajax (http post). The model I was expecting as a parameter was a class. It was inherited with some other class.
and in view
Simply removed duplicated fields from PurchaseOrder class and it worked like a charm.
我也有同样的错误。当我检查代码时,我发现在我的角度(字体端)端声明“GET”请求,并在 ASP.net(后端)端声明“POST”请求。在两侧设置 POST/GET 任意一项。然后解决了错误。
I have had the same error. When i check the code then i found that declare "GET" request in my angular (font-end) side and declare "POST" request in the ASP.net (back-end) side. Set POST/GET any one in both side. Then solved the error.
很可能,您的模型两次包含相同的属性。也许您正在使用 new 来隐藏基本属性。
解决方案是覆盖该属性或使用其他名称。
如果您分享您的模型,我们将能够详细说明。
Most likely, you have model which contains the same property twice. Perhaps you are using
new
to hide the base property.Solution is to override the property or use another name.
If you share your model, we would be able to elaborate more.
我有同样的问题,这就是我解决它的方法。我的 ViewModel 中有一个同名的重复属性。一个属性位于 BaseViewModel 中,另一个属性位于派生模型中。
我将其更改为
“现在工作正常”。
I had the same problem and this is how I solved it. I had a duplicate property with the same name in my ViewModel. One Property was in BaseViewModel and another is in derived Model.
I changed that to
Now it is working fine.
我有 2 个这样的模型属性,
奇怪的是它为这 2 个属性抛出了这个错误,哈哈..
I had 2 model properties like this
it is strange that it threw this error for these 2 haha..
我遇到了类似的问题,发现这是因为我有一个类似名称的公共财产(应该是私有的),只是大小写不同。
应该是
I had a similar problem and found that it was because I had a similarly named public property (that should have been private) that only differed in case.
should have been
我的问题不是在我的 C# 模型中,而是在我使用 AJAX 发布的 javascript 对象中。我使用 Angular 进行绑定,并且页面上有一个大写的
Notes
字段,而我的 C# 对象需要小写的notes
字段。更具描述性的错误肯定会很好。C#:
角度/Javascript:
I had the problem not in my C# model, but in the javascript object I was posting using AJAX. I'm using Angular for binding and had a capitalized
Notes
field on the page while my C# object was expecting lower-casenotes
. A more descriptive error would sure be nice.C#:
Angular/Javascript: