EF5 reports an error and cannot determine the subject of the "XXX" relationship. The added entities may have the same primary key.

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.