C# 初始化实体框架上下文的最佳方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1063730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 07:21:19  来源:igfitidea点击:

Best way to initialize an entity framework context?

c#entity-framework

提问by J.W.

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?

从 Ado.Net 背景来看,我更喜欢后面的 one-initialize in 方法,但第一个来自Stephen Walthe开发的示例。或者另一个问题,这有关系吗?

采纳答案by Craig Stuntz

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.

这确实很重要,因为上下文控制更改跟踪数据的生命周期,并且还会影响您在编辑对象时可以将哪些对象实例链接在一起,因为两个不同上下文中的对象不能相互关联。在我看来,您分享的示例来自 ASP.NET MVC 应用程序。在这种情况下,我通常为每个请求使用一个实体上下文,因为请求是短暂的,而且在更新请求中的对象时,必须获取其他对象并在它们之间创建关系是很常见的。

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

这似乎是“每个类一个上下文”选项的论据,但实际上并非如此。这更像是“每个工作单元一个上下文”的论据。

回答by IT Helper

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

一般来说:它是 ASP.NET 中每个请求的上下文和 WinForms/WPF 中每个窗口的上下文。

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

有一篇文章很好地解释了每个请求范式的上下文背后的推理: Entity Framework Object Context Scope

回答by NightOwl888

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.

嗯,“最好”的方式总是主观的。但是,向项目添加 UnitOfWorkScope 类可以大大简化事情 - 即您不必过多考虑创建对象上下文或将工作单元持久化回数据库。

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

有一篇很棒的文章解释了如何创建工作范围单元