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 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.
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.
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.
The first version is better and I would prefer it because
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With