Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework and deataching objects

When building a web application that uses entity framework in its data access layer, it is recommended to detach objects from the object context to allow objects to be garbage collected.

But since the web applications are all request -> response applications, the object context itself is not referenced any more by any live objects after the response is sent to the customer, and so the object context and its attached object should be available for garbage collection, since there is no live object referencing any of them.

Am I missing something here or detaching objects in not necessary in such scenario?

like image 259
Muhammad Soliman Avatar asked Nov 05 '22 18:11

Muhammad Soliman


1 Answers

I suspect the guidance you saw was talking about No-Tracking queries

No-Tracking queries definitely have some performance benefits for read intensive web-sites.

Objects are never attached, and tracked by identity, so you don't need to detach them, which avoids the cost of doing identity resolution during the materialization.

A no-tracking query looks like this:

var source = ctx.Staff;
source.MergeOption == MergeOption.NoTracking;

var staff = (from s in source
             where s.ID == 12 
             select s).First();

No tracking queries have another benefit over manually detaching entities: Manually detaching disconnects the entity from the rest of its entity Graph, where as, with no tracking queries you can retrieve a connected graph of entites that are all detached.

But there are some downsides to using non-tracking queries too: You can occasionally end up in situations where you read duplicate results because you've turned off identity resolution.

So unless you are really confident that your query is only going to return one copy of each entity, you should be careful, or you might end up with a UI bug.

Hope this helps

Alex

PS: This tip on ObjectContext lifetime might be helpful for you.

like image 183
Alex James Avatar answered Nov 13 '22 17:11

Alex James