0

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();
        }
     }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Kiemo
  • 47
  • 1
  • 6

1 Answers1

2

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();
undefined
  • 33,537
  • 22
  • 129
  • 198
  • Using DI makes sense, I hadnt thought of that. I dont quite understand the binding code, but thats becuase I am simplistic programmer (a vb.net coder to boot) and I think the code is MVC faire, whereas I am doing web forms. – Kiemo May 19 '12 at 02:36
  • yeah it definitely fits better with the MVC pattern however its defiantly doable for webforms see http://stackoverflow.com/a/6121250/1070291 – undefined May 19 '12 at 03:06