Disposing of object context in entity framework 4

不羁岁月 提交于 2019-12-02 19:37:01

I would implement IDisposable on the Repository class as well, so it can dispose the ObjectContext. If you return a different ObjectContext each time, you can run into problems when doing queries between those objects, as those are attached to different ObjectContexts, which will result in an exception.

Definition:

public class Repository : IDisposable
{
    DevEntities db = new DevEntities();

    public Customer GetCustomerByID(int id)
    {
        var customers = db.Customers.FirstOrDefault(c => c.CustomerId == id);

        return customers;
    }

    public Customer GetCustomerByPasswordUsername(string email, string password)
    {
        var customers = db.Customers.FirstOrDefault(c => c.Email == email && c.Password == password);

        return customers;
    }

    public void Dispose()
    {
        db.Dispose();
    }
}

Usage:

using(Repository r = new Repository())
{
  //do stuff with your repository
}

Doing this, your repository takes care of disposing the ObjectContext after you used it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!