简体   繁体   English

实体框架:Detach和AsNoTracking之间的区别

[英]Entity Framework: difference between Detach and AsNoTracking

My goal is to copy an existing Entity, slightly modify it, and insert the modified version. 我的目标是复制现有实体,稍微修改它,然后插入修改后的版本。

I have tried two different methods that both appear to work: 我尝试了两种似乎都有效的方法:

var thing = context.Things.Where(x => x.SomeID == someid).AsNoTracking().Single();
thing.AnotherID = 1234;
context.Things.AddObject(thing);
context.SaveChanges();

var thing = context.Things.Where(x => x.SomeID == someid).Single();
context.Detach(thing);
thing.AnotherID = 1234;
context.Things.AddObject(thing);
context.SaveChanges();

From what I can tell they both are accomplishing my goal. 据我所知,他们都在实现我的目标。 Is one of these better than the other, or are they both equally fine (or wrong!?) 其中一个比另一个好,还是它们都同样好(或错误!?)

The first version is better and I would prefer it because 第一个版本更好,我更喜欢它,因为

  • it expresses better that you don't want to track changes of the existing entity 它表示您不希望跟踪现有实体的更改
  • it doesn't attach the entity to the context in the first place while the second version attaches and then immediately detaches it (which most likely will also have slightly worse performance) 当第二个版本附加时,它不会将实体附加到上下文中,然后立即将其分离(这很可能性能稍差)
  • it perserves relationships (doesn't matter in this simple example, but generally) while detaching an entity only detaches the entity itself that you pass into Detach . 它持久化关系(在这个简单的例子中无关紧要,但一般而言),而分离实体只会分离你传递给Detach的实体本身。 Related children will stay attached which comes with the price that the relationships will be cleared (a navigation collection of child entities for example would be emptied, a reference navigation property would be set to null ) since EF does not allow object graphs with a mix of attached and detached entities. 相关的子项将保持附加,其中包含将清除关系的价格(例如,子实体的导航集合将被清空,参考导航属性将被设置为null ),因为EF不允许具有混合的对象图形附加和分离的实体。

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

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