Should I be disposing EF4.0 ObjectContexts?
I've got a simple UnitOfWork pattern going with Entity Framework 4开发者_StackOverflow, like so:
public class UnitOfWork
{
private readonly myEntities _context;
public UnitOfWork()
{
_context = new myEntities();
}
public myEntities Context { get { return _context; } }
public void SaveChanges()
{
_context.SaveChanges();
}
public void Finish()
{
_context.Dispose();
}
}
My question is this: do I need that Finish method? Do I need to explicitly call Dispose on my ObjectContext-derived entity object, or should I just let the garbage collector take care of it?
Since the EF context is disposable and at its core represents a database connection yes, you should Dispose() it.
To make it a little easier on the consumers of your UnitOfWork class, I would make it implement IDisposable as well as opposed to providing a Finish() method. That way it can be used in a using block.
加载中,请稍侯......
精彩评论