One ObjectContext per repository vs per method

205 Views Asked by At

Approach 1

public class MyEntityRepository
{
private MyEntityContainer datacontext = new MyEntityContainer();

public IQuarable<VMModel1> Method1()
{
 //datacontext  used here in linq query

}

public IEnumerable<VMModel2> Method2()
{
 //datacontext  used here in linq query

}

}

Approach 2

public class MyEntityRepository
{


public IQuarable<VMModel1> Method1()
{
 using (var context = new MyEntityContainer())
{    
    // Perform data access using the context
}

}

public IEnumerable<VMModel2> Method2()
{
 using (var context = new MyEntityContainer())
{    
    // Perform data access using the context
}

}

}

My Question is which approach is better and pros and cons of using each approach

1

There are 1 best solutions below

2
On

Actually I prefer ObjectContext per HTTP Request. Shared context per request solves problem of managing attached entities. As far as you have only one context, you just don't worry about it at all. It's easier to manage context scope: at the end of the request just SaveChanges and Dispose it.

Here is how it works:

public abstract class AbstractRepository<T> where T : class
{
    /// <summary>
    /// Common context per request
    /// </summary>
    protected static ocm Context
    {
        get 
        { 
            if (HttpContext.Current != null)
            {
                var db = HttpContext.Current.Items["DbContext"] as MyObjectContext
                if (db == null)
                {
                    db = new MyObjectContext();
                    HttpContext.Current.Items.Add("DbContext", db);
                }
                return db;
            }
            return new MyObjectContext();
        }
    }

    public T Get(decimal id)
    {
        return Context.Set<T>().Find(id);
    }

    public virtual T Get(int id)
    {
        return Context.Set<T>().Find(id);
    }

    public List<T> GetAll()
    {
        return Context.Set<T>().ToList();
    }

    public void Add(T obj)
    {
        Context.Set<T>().Add(obj);
    }

    public void Remove(T obj)
    {
        Context.Set<T>().Remove(obj);
    }

    public void Attach(T obj)
    {
        Context.Set<T>().Attach(obj);
    }

    public void SaveChanges()
    {
        Context.SaveChanges();
    }
}

Let me know if you have questions regarding the usage or Disposing of the context.