简体   繁体   中英

Entity Framework retrieving different instances

I assumed that for a given ObjectContext, if I do a query and retrieve a unique object (ieusing primary key(s)), a second query using the same ObjectContext would give me the very same instance of the object.

However, this is not necessarily the case.

Can someone shed some light on this?

Thanks!

Here is some code: (in this case I have a composite key)

var x = context.MyEntity.FirstOrDefault(e => e.Key1 == 1 && e.Key2 == 5);
var y = context.MyEntity.FirstOrDefault(e => e.Key1 == 1 && e.Key2 == 5);  
var isSame = x == y;  

UPDATE

I believe the answer to this problem lies in the MergeOption for the entities. I noticed that the ones that are not working are set to NoTracking, as opposed to the AppendOnly option which is the default. This is probably the root of the problem I am having.

The problem is due to an incorrect MergeOption setting. In this particular case it was set incorrectly to NoTracking.

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