[英]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 第一个版本更好,我更喜欢它,因为
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.