实体框架:分离和AsNoTracking区别 [英] Entity Framework: difference between Detach and AsNoTracking

查看:121
本文介绍了实体框架:分离和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!?)

推荐答案

第一版更好,因为


  • 它表达更好,你不想跟踪现有实体的变化,我宁愿它

  • 它不实体附加到上下文在首位,而第二版本附加然后立即分离它(这很可能也会有性能略差)

  • <李>它perserves的关系(在这个简单的例子并不重要,但通常情况下),而分离的实体只有分离,你传递到分离实体本身。相关的孩子将保持连接附带的关系将被清除(子实体例如导航集合将被清空,参考导航属性将被设置为空),因为EF不允许对象图形与连接和分离实体的组合。
  • 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. 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.

这篇关于实体框架:分离和AsNoTracking区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆