An item with the same key has already been added
Let me shed some light on it for you. This is a non-descript error from Visual Studio but it points to a problem with the generation of properties or relationships. The most notable problems are found with either:
Problem #1:Similarly Named Properties.
For example you use myproduct and MyProduct. Although acceptable in C# - this is interpreted as the same when generating the controller. Check your class for any duplicates and resolve accordingly.
Problem #2: Multiple Relationship References Using The Same Field.
If you accidentally double-map a property [column] in a relationship - you will get this error. The easiest way is to use SQL Server Management Studio and look at each relationship. Ensure that there are no mappings that cross over. If you find the problem in SQL Server then go back to your Code First and figure out where the wheels fell off of the bus. This can easily happen if you go to Add a key and then stop before you make the appropriate changes. SSMS remembers it for you - and if you save, you end up with FK_TableName_TableName - which will cause the problem.
If you fix the problem for #2 in SQL Server Management Studio then use the Entity Framework > Reverse Engineer Code First in Visual Studio to fix your class and map.
2 comments:
Not sure what you mean by "mappings that cross over". Could you elaborate a little more?
By that I mean that your Constraints are valid and not duplicated. If you have two or more of the same (such as adding a new item but not defining what it maps to) - which is the default behavior of SSMS, then the EF will not be able to handle it.
Also, the Entity Framework doesn't like hyphens in database structures so watch out for that one too. IE: my-database or my-table.
Post a Comment