Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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."


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...