ArgumentException: An item with the same key has already been added
Asked Answered
M

26

170

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>

Morten answered 13/4, 2011 at 10:59 Comment(1)
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.Lowgrade
S
267

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.

Summersault answered 13/4, 2011 at 11:3 Comment(5)
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")Toby
@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.Summersault
Would someone know how to identify which is "the same key?"Spies
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.Neritic
PS: this is allowed in MVC3, but not in MVC5. No sure why this has been changed.Radiochemical
C
24

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.

Clamatorial answered 26/8, 2012 at 19:52 Comment(1)
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:userInvolute
E
19

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

Ebullition answered 13/9, 2013 at 18:19 Comment(0)
D
14

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;}
Demetra answered 26/11, 2012 at 19:3 Comment(0)
G
9

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">
Grati answered 13/12, 2013 at 0:20 Comment(2)
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..Grati
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.Jacksonjacksonville
C
6

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

Chronometry answered 27/9, 2013 at 17:13 Comment(0)
M
3

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

Morten answered 17/4, 2011 at 4:32 Comment(0)
W
2

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.

Whitcher answered 1/4, 2019 at 13:31 Comment(0)
M
2

2021 - March

Demo on dotnetfiddle

In my case, the key in the dictionary is duplicated. enter image description here

Magnetometer answered 21/3, 2021 at 8:16 Comment(0)
L
1

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.

Lydon answered 7/8, 2014 at 7:31 Comment(0)
B
1

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; }
Benedick answered 31/10, 2014 at 5:47 Comment(0)
B
1

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; }
Benedick answered 15/4, 2015 at 21:58 Comment(0)
C
1

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.

Cutthroat answered 3/6, 2015 at 15:0 Comment(0)
A
1

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

Archway answered 3/8, 2015 at 6:57 Comment(0)
L
0

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.

Longitudinal answered 3/7, 2016 at 15:15 Comment(0)
F
0

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)

Freund answered 12/4, 2017 at 12:31 Comment(0)
B
0

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

Barnes answered 30/6, 2017 at 11:5 Comment(0)
O
0

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
Otology answered 21/2, 2018 at 5:15 Comment(0)
W
0

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.

Waltner answered 14/10, 2018 at 20:59 Comment(0)
R
0

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.

Riarial answered 29/6, 2019 at 13:5 Comment(0)
A
0

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

Averse answered 24/4, 2020 at 7:52 Comment(0)
F
0

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

Fancywork answered 22/5, 2020 at 9:33 Comment(0)
G
0

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
}
Gustave answered 7/3, 2021 at 17:22 Comment(0)
T
0

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

                }

            }
Tuna answered 25/3, 2021 at 13:3 Comment(0)
C
0

When you use context.Entity.FromSqlRaw() , SQL query column names must equal to C# class property names.

Collimate answered 16/12, 2022 at 11:34 Comment(0)
M
-1

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.

Mosier answered 8/2, 2022 at 20:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.