开发者

Should I be disposing EF4.0 ObjectContexts?

开发者 https://www.devze.com 2023-02-25 06:07 出处:网络
I\'ve got a simple UnitOfWork pattern going with Entity Framework 4开发者_StackOverflow, like so: public class UnitOfWork

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消