Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!?)

like image 542
TTT Avatar asked Nov 22 '13 20:11

TTT


People also ask

What is AsNoTracking in Entity Framework?

The AsNoTracking() extension method returns a new query and the returned entities will not be cached by the context (DbContext or Object Context). This means that the Entity Framework does not perform any additional processing or storage of the entities that are returned by the query.

How much faster is AsNoTracking?

What did surprise me was the size of the differences.. for example AsNoTracking performance is 3.56x faster than tracking when we are pulling back 5K entities.. which is a relatively small record set.

How do I turn off change tracking in Entity Framework?

In Entity Framework, change tracking is enabled by default. You can also disable change tracking by setting the AutoDetectChangesEnabled property of DbContext to false. If this property is set to true then the Entity Framework maintains the state of entities.


1 Answers

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. 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.
like image 64
Slauma Avatar answered Oct 08 '22 04:10

Slauma