简体   繁体   中英

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

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.

I have that exactly problem too. A class named 'Paquete_PartNumber' throws the same error. Removing the underscore solves the issue.

Using EF 6.0.1.

Removing the underscore solved my problem as well. However the real issue was the naming convention.

Renaming the navigation collection property on the one side of the relationship solved the problem without having to change the table name in the database

I tried removing the underscore but that didn't work for me. It turned out that in my case defining a (model)class in plural (+s) messed it up. After removing the s it worked again. Very weird but it solved it.

Using EF 6.0.0.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM