初始化实体框架上下文的最佳方式? [英] Best way to initialize an entity framework context?

查看:94
本文介绍了初始化实体框架上下文的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

初始化实体框架上下文时。

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

从Ado.Net背景来看,我更喜欢方法一初始化,但第一个是从 Stephen Walthe 开发的示例。或者另一个问题,是否重要?

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?

推荐答案

这很重要,因为上下文控制变更跟踪数据的生命周期,并且还会影响在编辑对象时可以链接在一起的对象实例,因为两个不同上下文中的对象彼此之间不能有关系。它看起来像我正在分享的例子来自于ASP.NET MVC应用程序。在这种情况下,我通常每个请求使用一个实体上下文,因为请求是短暂的,并且由于在更新请求中的对象时,通常需要获取其他对象并在它们之间建立关系。

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

这篇关于初始化实体框架上下文的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆