ChatGPT解决这个技术问题 Extra ChatGPT

An item with the same key has already been added

I get this error whenever I submit the form also the action method is not being called because of this:

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>
      <%} %>

You need to add more context to this. Show us the controller code and describe the exact actions you are taking. Do a little debugging on your own so that your questions are more verbose and not just giant lumps of code/stack.
I checked my JSON I was posting very very closely and found a duplicate property - one spelled CustomerID and one spelled CustomerId - via a javascript typo both properties had gotten added to the JSON I was posting, so just a heads up that solved this issue for me.

A
Aliostad

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.


In C#, say, if you have variable1 and Variable1 (it'll throw the error). Also, check to make sure there's no similar edmx names (table column has "CURRENCY", one of Navigation Properties name had "Currency")
@Naveen Great it is fixed! I see that how this could compile but throw error here. Some parts of the framework (unlike C#) is case-insensitive.
Would someone know how to identify which is "the same key?"
I started getting this after I fiddled with some view models (added an Id property). The fault was that the JS was already putting an "id" (lowercase id) onto the object for some UI management, but when submitting, the JSON object had both "Id" and "id" properties, which maps to the same key in ASP.NET's model binder, hence this error.
PS: this is allowed in MVC3, but not in MVC5. No sure why this has been changed.
M
Mukus

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.

public class BaseviewModel{
  public int UserId { get; set; }
}


 public class Model : BaseViewModel
 {
     public int UserId { get; set; }
 }

I changed that to

public class BaseviewModel{
   public int UserId { get; set; }
}


public class Model : BaseViewModel
{
    public int User_Id { get; set; }
}

Now it is working fine.


Thanks, just a quick fyi, this also occurs even if the base and the model have the same attribute name with different case e.g Base:User, Model:user
b
benPearce

I had 2 model properties like this

public int LinkId {get;set;}
public int LinkID {get;set;}

it is strange that it threw this error for these 2 haha..


H
Hal

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.

public string PropertyName {get;set;} // actually set propertyName, get propertyName
public string propertyName {get;set;}

should have been

public string PropertyName {get;set;} 
private string propertyName {get;set;}

J
Jason Goemaat

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-case notes. A more descriptive error would sure be nice.

C#:

class Post {
    public string notes { get; set; }
}

Angular/Javascript:

<input ng-model="post.Notes" type="text">

It's a slightly different answer, none of my C# classes have duplicate properties with different cases, but the JSON that was getting sent to my controller did. Thought it may come in handy with other people searching for the same issue if they can't find the problem in their C# code..
Same as Goematt. The JSON object that was being sent had duplicate names even though the c# object I was binding to was completely ignoring those keys, it still failed. This is dumb, maybe even a bug in my mind. I'm not controlling the JSON object being sent, so I can't account for what all extra fields are being sent.
M
Mina Gabriel

I had the same issue , i was foreach looping over my object and adding the result into a Dictionary<string, string> and i had a `Duplicate in the key from the database

 foreach (var item in myObject)
        {
            myDictionary.Add(Convert.ToString(item.x), 
                                   item.y);

        }

item.x had a duplicate value


u
user650922

I found the answer.It was because of the variables. Like int a and string a. there were two variables with the same name.


A
Ahmet Remzi EKMEKCI

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

public static AClass
{
    public static Dictionary<string, string> ADict = new Dictionary<string, string>()
        {
            {"test","value1"},{"test","value2"},
        };
}

Explanation ADict has "test" key added twice. So, when you call the static class, it throws the exception.


b
bvoleti

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.


J
Jeremy Cook

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".

[Index(IsUnique = true)]
public string Thing1 { get; set; }

[Index(IsUnique = true)]
public string Thing2 { get; set; }

J
Jeremy Cook

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.

public Guid CreatedById { get; private set; }
// Commented out so I can scaffold: 
// public virtual UserBase CreatedBy { get; private set; }

J
JasonWilczak

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:

var currentModel = result.Data;

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 send currentModel to the server.

In my Javascript, however, I did this, instead:

currentModel.items = getData();

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 AND currentModel.Items

A simple change from "items" to "Items" fixed the problem.


a
abiNerd

My problem was that I had a @Url.Action and I had sent through a value for the same property twice


M
Mariusz

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:

@Html.EditorFor(model => model.MyProperty, "MyCustomTemplateName", "MyPropertyField", this.ViewData)

To resolve issue I had to remove passing ViewData object. So at the end I had:

@Html.EditorFor(model => model.MyProperty, "MyCustomTemplateName", "MyPropertyField")

Hope it helps.


A
AlfredBauer

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)


k
kubajs

In my case the root of the problem was duplicate property name in the client json which only differed by case sensitivity.


u
user9375338

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:

select @column1, @column2

Adding column names will prevent the error:

select @column1 as col1, @column2 as col2

A
Adeel Shekhani

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.

public class PurchaseOrder : CreateUpdateUserInfo
    {
        public PurchaseOrder()
        {
            this.Purchase_Order_Items = new List<clsItem>();
        }

        public int purchase_order_id { get; set; }
        public Nullable<int> purchase_quotation_id { get; set; }
        public int supplier_id { get; set; }
        public decimal flat_discount { get; set; }
        public decimal total { get; set; }
        public decimal net_payable { get; set; }
        public bool is_payment_complete { get; set; }
        public decimal sales_tax { get; set; }
        public DateTime CreatedOn { get; set; }
        public int CreatorUserID { get; set; }
        public DateTime UpdatedOn { get; set; }
        public int UpdatorUserID { get; set; }
        public bool IsDeleted { get; set; }
        public List<clsItem> Purchase_Order_Items { get; set; }
    }

 public class CreateUpdateUserInfo
    {
        public DateTime CreatedOn { get; set; }
        public int CreatorUserID { get; set; }
        public string CreatorUserName { get; set; }
        public DateTime UpdatedOn { get; set; }
        public int UpdatorUserID { get; set; }
        public string UpdatorUserName { get; set; }
        public bool IsDeleted { get; set; }
    }

and in view

                var model = {
                supplier_id : isNaN($scope.supplierID) || 0 ? null : $scope.supplierID,
                flat_discount : 0,
                total : $scope.total,
                net_payable :  $scope.total,
                is_payment_complete :  true,
                sales_tax:0,
                Purchase_Order_Item: $scope.items
            };
            var obj = {
                method: 'POST',
                url: 'Purchase/SaveOrder',
                dataType: 'json',
                data: JSON.stringify(model),
                headers: { "Content-Type": "application/json" }
            };

            var request = $rootScope.AjaxRequest(obj);
            request.then(function (response) {
                var isError = response.data.MessageType === 1;
                $rootScope.bindToaster(response.data.MessageType,response.data.Message);
                //$('html, body').animate({ scrollTop: 0 }, 'slow');
                if(!isError){
                    //$scope.supplierID =undefined;
                }
            }, function (response) {
                $rootScope.bindToaster(2,response.data);
                console.log(response);
            });

Simply removed duplicated fields from PurchaseOrder class and it worked like a charm.


S
Sanjib Dhar

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.


V
Vikas

I faced similar exception. Check if all columns has header names( from select query in database) with exactly matching property names in model class.


L
LuTheZy

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; }


A
Ahmad

I had this exact error, not because of property names, but for having duplicate custom attribute values.

class Person {
  [Column("first_name")]
  public string FirstName { get; set; }

  [Column("first_name"]  // I forgot to change the custom attribute value
  public string LastName { get; set; }

  public static IEnumerable<Name> Names = db.Query<Name>(""); // error
}

N
Nguyễn Văn Phong

2021 - March

Demo on dotnetfiddle

https://i.stack.imgur.com/Aliu9.png


T
Tiago Santos

In my case it was because I used JoinAlias within a for.

            foreach (ISearchSpecsFilter item in searchFilter.SpecsFilter) {

                if (item.MinValue + item.MinValue != 0) {

                    result = result
                        .WithSubquery
                        .WhereExists(
                            workDetailEntity
                                .JoinAlias(j => j.WorkDetailLabel, () => workDetailLabelEntity)
                                .JoinAlias(j => workDetailLabelEntity.WorkLabel, () => workLabelEntity)
                                .JoinAlias(j => workDetailLabelEntity.WorkUnitMeasureType, () => workUnitMeasureTypeEntity)
                                .Where(w => w.Work.WorkId == workEntity.WorkId && w.Value >= item.MinValue && w.Value <= item.MaxValue && workLabelEntity.WorkLabelId == item.WorkLabelId && workUnitMeasureTypeEntity.WorkUnitMeasureTypeId == (int)item.WorkUnitMeasure)
                                .Select(s => s.Work.WorkId)
                        );

                }

            }

C
Chamila Maddumage

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.


关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now