简体   繁体   中英

EF6: Multiple added entities may have the same primary key

I've inherited a database and I need to insert data using EF6. I get the error:

DbUpdateException: Unable to determine the principal end of the 'POSModel.FK_KitMemberTaxRaw_KitMemberSaleReturnRaw_KitMemberSaleReturnRowId' relationship. Multiple added entities may have the same primary key. 

I deserialize XML to the POCO objects using DataContractSerializer. I'm using the object references from the xml document's structure to define the relationships. The POCO objects are generated using a t4 script provided from the NuGet package (which does not work with either deserializer well at all!)

I've decorated KitMemberTaxRaw like so:

[ForeignKey("KitMemberSaleReturnRaw")]
public virtual KitMemberSaleReturnRaw KitMemberSaleReturnRaw { get; set; }

[ForeignKey("KitMemberKitMemberSaleReturnRaw")]
public virtual KitMemberKitMemberSaleReturnRaw KitMemberKitMemberSaleReturnRaw { get; set; }

The KitMemberTaxRaw table may be joined to either table KitMemberKitMemberSaleReturnRaw or KitMemberSaleReturnRaw (but not both).

How does EF determine 'the principal end of the relationship'?

The issue turned out to be EF6 was not able to automatically understand a table with links to a parent and an optional grand parent. The navigation properties generated by the Microsoft provided template were correct but insufficient.

To cure the issue I manually created temporary primary keys for the relationship it did not understand.

Note: The DataContractSerializer class I used created the POCO objects creates an array for the instantiated navigation properties. I had to change the template to generate IList<> properties instead of ICollection<>. At run time there were errors because the array could not be dynamically resized.

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