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
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:
Let me know if you have questions regarding the usage or Disposing of the context.