Raheel Khan Raheel Khan - 4 days ago 4
C# Question

One to many relationship in Entity Framework 6

I have two simple tables that have to map to columns in an existing database:

public class StockItem
{
public System.Guid pkStockItemID { get; set; }

public virtual List<StockItem_ExtendedProperties> ExtendedProperties { get; set; }
}

public class StockItem_ExtendedProperties
{
public System.Guid pkStockItem_ExtendedPropertiesID { get; set; }

public System.Guid fkStockItemId { get; set; }

public virtual StockItem StockItem { get; set; }
}


Following are the configuration classes for both:

public StockItemConfiguration ()
{
this.HasMany(item => item.ExtendedProperties)
.WithRequired(property => property.StockItem)
.HasForeignKey(property => property.fkStockItemId)
.WillCascadeOnDelete();
}

public StockItem_ExtendedPropertiesConfiguration ()
{
this.HasRequired(property => property.StockItem)
.WithMany(item => item.ExtendedProperties)
.HasForeignKey(property => property.fkStockItemId)
.WillCascadeOnDelete();
}


This results in the error:
The item with identity 'StockItem_ExtendedProperties' already exists in the metadata collection. Parameter name: item
.

It appears that defining the relationship from both sides of the table is causing the error. However, removing the configuration from either side still results in the same error.

In addition to how to fix the above, I'd like to know what the reason is and which of the two tables in such a relationship should be configured. Thanks.

Answer

Turns out the problem was the underscore in the entity name StockItem_ExtendedProperties. Removing that got rid of the error. Using EF 6.0.0.0 which was the latest available version via NuGet.

Comments