Scenario: the relationship between the user table and the order table is one-to-many, that is, a userinfo corresponds to multiple order tables.
If I create a user in EF, create three orders, and then associate the user with the three orders, there is no problem.
However, if I want to create two users and six orders and separate them, an error is reported.
The subject of the "XXX" link cannot be determined. The added entities may have the same primary key.
The reason may be:
When we add two users, the primary keys of the two user IDs are all 0, so when they are saved to the database, an error is returned..(Q: But for orders 1 to 6, their ID is also the primary key, and it is also 0. Why not report an error ?)
Solution
1: either add data in your userinfo primary table one by one. for example, first add user 1 and then save the relationship between user 1 and order 123. create user 2 and save the relationship between user 2 and order 456.
2: When adding userinfo, set a false ID. For example, set userinfo1's ID to 1 and userinfo2's ID to 2. This is the false ID we manually set, then, when EF associates user 1 with order 123, user 2 with order 456, the primary key of user 1 and user 2 is different, therefore, it can be determined that it is two different subjects.
When EF is actually executed to the database, because ID is the primary key, EF does not care about the fake ID primary key we manually created.
3: equivalent to version 1. We first save topic user 1 and user 2 to the database, so that their IDs will be different, the system will not prompt "the primary keys of the added entities may be the same"
References
Http://stackoverflow.com/questions/8530581/multiple-added-entities-may-have-the-same-primary-key-in-entity-framework
Http://www.cnblogs.com/tukzer/archive/2013/04/20/3033326.html