Entity Framework: the difference between Detach and AsNoTracking

My goal is to copy an existing object, modify it a bit, and paste the modified version.

I tried two different methods that both 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 say, they both achieve my goal. Is one of them better than the other, or are they both equally good (or wrong !?)

+10
c # entity-framework
Nov 22 '13 at 20:31
source share
1 answer

The first version is better, and I would prefer it because

  • it expresses better that you do not want to track changes to an existing object.
  • it does not attach the object to the context in the first place, until the second version is attached, and then immediately separates it (which, most likely, will also have slightly worse performance).
  • it maintains the relationship (it doesn't matter, in this simple example, but in general), while detaching the object only separates the object itself that you pass to Detach . Associated children will remain attached, which are associated with the price at which the relations will be cleared (for example, a collection of children will be created, the navigation reference property will be set to null ), because EF does not allow graphs of objects with a combination of attached and separate objects.
+15
Nov 23 '13 at 14:18
source share



All Articles