C# – Reuseable ObjectContext or new ObjectContext for each set of operations

cdata-access-layerlinq-to-entitiesobjectcontext

I'm new to the Entities Framework, and am just starting to play around with it in my free time. One of the major questions I have is regarding how to handle ObjectContexts.

Which is generally preferred/recommended of these:

This

public class DataAccess{

    MyDbContext m_Context;

    public DataAccess(){
        m_Context = new MyDbContext();        
    }

    public IEnumerable<SomeItem> GetSomeItems(){
        return m_Context.SomeItems;
    }

    public void DeleteSomeItem(SomeItem item){
        m_Context.DeleteObject(item);
        m_Context.SaveChanges();
    }
}

Or this?

public class DataAccess{

    public DataAccess(){ }

    public IEnumerable<SomeItem> GetSomeItems(){
        MyDbContext context = new DbContext();
        return context.SomeItems;
    }

    public void DeleteSomeItem(SomeItem item){
        MyDbContext context = new DbContext();
        context.DeleteObject(item);
        context.SaveChanges();
    }
}

Best Answer

The ObjectContext is meant to be the "Unit of Work".

Essentially what this means is that for each "Operation" (eg: each web-page request) there should be a new ObjectContext instance. Within that operation, the same ObjectContext should be re-used.

This makes sense when you think about it, as transactions and change submission are all tied to the ObjectContext instance.

If you're not writing a web-app, and are instead writing a WPF or windows forms application, it gets a bit more complex, as you don't have the tight "request" scope that a web-page-load gives you, but you get the idea.

PS: In either of your examples, the lifetime of the ObjectContext will either be global, or transient. In both situations, it should NOT live inside the DataAccess class - it should be passed in as a dependency

Related Topic