What is the best approach to set up an entity framework context?

c# entity-framework

Question

whenever an entity framework context is initialized.

Initializing at the class level is one option.

public class EntityContactManagerRepository
    : ContactManager.Models.IContactManagerRepository
{
    private ContactManagerDBEntities _entities = new ContactManagerDBEntities();

    // Contact methods
    public Contact GetContact(int id)
    {
        return (from c in _entities.ContactSet.Include("Group")
                where c.Id == id
                select c).FirstOrDefault();
    }
}

The alternative is to initialize at the level of the method.

public class EntityContactManagerRepository
    : ContactManager.Models.IContactManagerRepository
{    
    // Contact methods
    public Contact GetContact(int id)
    {
       using (var entities = new ContactManagerDBEntities())
           return (from c in entities.ContactSet.Include("Group")
               where c.Id == id
               select c).FirstOrDefault();
    }
}

Having experience with Ado.Net, I prefer the initialize in method, however the first one is from the Walthe, Stephen example. Or maybe another query: Does it even matter?

1
37
2/4/2011 1:07:20 AM

Accepted Answer

It does important since objects on two separate contexts cannot have a connection with each other. Furthermore, the context affects which object instances you may link together while editing the objects and determines the duration of change tracking data. The samples you're providing seem to be taken from an ASP.NET MVC application. Due to requests' short lifespans and the frequent need to retrieve more objects and establish associations between them when altering an object inside a request, I often utilize one entity context per request in this situation.

On the other side, as it records changes to more and more objects, an entity context will eat up memory if you leave it around for a long period.

Although it could seem that this supports the "one context per class" option, it actually doesn't. It more closely resembles a justification for "one context per unit of labour."

31
6/30/2009 2:12:25 PM

Popular Answer

In general, WinForms/WPF uses context per window while ASP.NET uses context per request.

The context per request paradigm's rationale is explained in great detail in the following article: Context of Entity Framework Objects



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow