Sunday, January 18, 2009

Entity Framework - Don't Forget to Detach

Often in the web programming model, we make use of disconnected data sets. When using LINQ-to-Entity to fetch data, you have to remember to call the Detach method of the context. If you do not detach the object, the context continues to maintain a reference which keeps it from being garbage collected.

Here's an example:
public Customer GetById(int aId) {
DataEntities de = new DataEntities();
var retVal = (from iterCust in de.Customers
where iterCust.Id = aId
select iterCust).FirstOrDefault();
de.Detach(retVal); //detach the object from the context
return retVal;
}

You do not have to do this when you set the NoTracking MergeOption (set de.Customer.MergeOption).

1 comment:

Alf said...

As far as you do not keep a reachable reference to your dbcontext, both the context and entities can be collected by GC. Also, you're missing Dispose method to be called on the dbcontext.
Please, do not misinform folks.