Is there any “best practice” on how to handle the Datacontext in Entity Framework 4?
Currently, I’m doing something like this in every window:
public class MyWindow()
{
MyEntities() _entities;
MyWindow()
{
_entities = new MyEntities();
InitializeComponent();
}
}
and then the loading into a datagrid like this:
myGrid.ItemsSource= _entities.MyTable;
This is not really clever, because ErrorHandling is made impossible on that.
I’d rather go for a Connection-Class and do something like this:
public class MyData()
{
public IQueryable<Product> GetAllProducts()
{
using(MyContext context = new MyContext())
{
return context.Products;
}
}
}
But first, this creates a new context-instance every time – isn’t this bad?
Or should I rather handle a global static DataContext in my Connection-Class? Doesn’t get this static variable very overloaded?
public class MyData()
{
private static MyContext Context = new MyContext();
public IQueryable<Product> GetAllProducts()
{
return Context.Products;
}
}
In entity framework, an
ObjectContext/DbContextis a unit of work, their lifetime is meant to be short.Having a static context is a definite no-no, as this would use a lot of memory with change tracking entities (every change tracked entity would be cached and stored until the context is disposed).
Wrapping the context in a using, like your ‘Connection-Class’ example is the right way to go about doing this. This would often be referred to as a Service.
An example service:
Be sure to call either
ToArray()orToList()or useyield return(as in my example) when returning a collection of results in a block where the context will be disposed. Failing to do this would mean that when your results are used, deferred execution will attempt to use the disposed context which will result in an exception at runtime.