简体   繁体   English

实体框架检索不同的实例

[英]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. 我假设对于给定的ObjectContext,如果我执行查询并检索到一个唯一的对象(即使用主键),则使用相同ObjectContext进行的第二次查询将为我提供该对象的完全相同的实例

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. 我相信这个问题的答案在于实体的MergeOption。 I noticed that the ones that are not working are set to NoTracking, as opposed to the AppendOnly option which is the default. 我注意到那些不起作用的设置为NoTracking,这与默认的AppendOnly选项相对。 This is probably the root of the problem I am having. 这可能是我遇到的问题的根源。

The problem is due to an incorrect MergeOption setting. 问题是由于不正确的MergeOption设置。 In this particular case it was set incorrectly to NoTracking. 在这种情况下,它被错误地设置为NoTracking。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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