asp.netentity-framework-4webformsobjectcontext

Entity framework, consuming context in webform app


Rather simple question regarding entity framework and how to consume the objectcontext.

In a asp.net webform application I am implementing most of data getters in a data class and trying to determine if its better (in a generic sense of better) to have a private context for the entire class or declare a context in each of the methods.

Example 1:

public class Data
{
     private MyEntity context = new MyEntity();
     public Customer GetCustomer()
     {
        return context.Customer.Single();
     }

     public Order GetOrder()
     {
        return context.Order.Single();
     }
}

Or Example 2:

public class Data
{
     public Customer GetCustomer()
     {
        using (MyEntity ctx = new MyEntity()) 
        {
           return context.Customer.Single();
        }
     }

     public Order GetOrder()
     {
        using (MyEntity ctx = new MyEntity()) 
        {
           return context.Order.Single();
        }
     }
}

Solution

  • Personally im a big fan of using a shared context across your whole post back, however neither of these scenarios really achieve this. My personal preference is to use a dependency injection container such as ninject to manage the lifecycle of your EF context. This means that you can make your whole postback transactional.

    in terms of implementation I would go for soemthing like the following:

    public class Data
    {
        private MyContext _context;
        public Data(MyContext context)
        {
           _context = context;
        }
    
         public Customer GetCustomer()
         {
            return _context.Customer.Single();
         }
    
         public Order GetOrder()
         {
            return _context.Order.Single();
         }
    }
    

    with a binding similar to:

    Bind<MyContext>().ToSelf().InRequestScope();