Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to initialize an entity framework context?

When initialize an entity framework context.

One is to initialize at class level, such as

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 other way is to initialize at the method level.

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();
    }
}

From an Ado.Net background, I prefer the later one-initialize in method, but the first one is from the example developed by Stephen Walthe. Or another question, does it matter at all?

like image 434
J.W. Avatar asked Jun 30 '09 13:06

J.W.


People also ask

Does DbContext need to be disposed?

As Daniel mentioned, you don't have to dispose the dbContext. From the article: Even though it does implement IDisposable, it only implements it so you can call Dispose as a safeguard in some special cases. By default DbContext automatically manages the connection for you.

What is DbContext and DbSet in Entity Framework?

DbContext generally represents a database connection and a set of tables. DbSet is used to represent a table.

Is EF core thread-safe?

DbContext is not thread-safe. Do not share contexts between threads. Make sure to await all async calls before continuing to use the context instance.


3 Answers

It does matter, because the context controls the lifetime of change tracking data, and also impacts which object instances you can link together when you edit the objects, since objects on two different contexts cannot have a relationship with each other. It looks to me like the examples you're sharing come from an ASP.NET MVC application. In this case, I generally use one entity context per request, since requests are short-lived, and since it's common, when updating an object in a request, to have to fetch other objects and create relationships between them.

On the other hand, you don't want to keep an entity context around for a long time, because it will chew up memory as it tracks changes to more and more objects.

This may seem like an argument for the "one context per class" option, but it isn't, really. It's more like an argument for "one context per unit of work."

like image 92
Craig Stuntz Avatar answered Oct 05 '22 19:10

Craig Stuntz


Generally speaking: it's context per request in ASP.NET and context per window in WinForms/WPF.

There's an article that explains quite well the reasoning behind the context per request paradigm: Entity Framework Object Context Scope

like image 45
IT Helper Avatar answered Oct 05 '22 19:10

IT Helper


Well, the "best" way is always subjective. However, adding a UnitOfWorkScope class to the project can simplify things greatly - namely you don't have to think too much about creating the object context or persisting the Unit of Work back to the database.

There is a great article that explains How To Create a Unit of Work Scope.

like image 20
NightOwl888 Avatar answered Oct 05 '22 19:10

NightOwl888