C#中的实体框架:你的资料库类中正确使用的DbContext类 [英] c# entity framework: correct use of DBContext class inside your repository class

查看:1939
本文介绍了C#中的实体框架:你的资料库类中正确使用的DbContext类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用来实现我的仓库类,你可以看到下面

I used to implement my repository classes as you can see below

public Class MyRepository
{
      private MyDbContext _context; 

      public MyRepository(MyDbContext context)
      {
          _context = context;
      }

      public Entity GetEntity(Guid id)
      {
          return _context.Entities.Find(id);
      }
}



不过,我最近看了这文章,其中说,这是一个不好的做法有在你的仓库私有成员数据上下文: http://devproconnections.com/development/solving-net -scalability-问题

现在,从理论上说文章是正确的:因为的DbContext实现IDisposable最正确的实施将以下

Now, theoretically the article is right: since DbContext implements IDisposable the most correct implementation would be the following.

public Class MyRepository
{
      public Entity  GetEntity(Guid id)
      {
          using (MyDbContext context = new MyDBContext())
          {
              return context.Entities.Find(id);
          }
      }
}



然而,根据该其它文章处置的DbContext是不是必要的:的http:// blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext.html

这两个文章是正确的?我很困惑。
拥有的DbContext在你的仓库类可以真正造成可扩展性问题的第一篇文章暗示?

Which of the two articles is right? I'm quite confused. Having DbContext as private member in your repository class can really cause "scalability problems" as the first article suggests?

推荐答案

不应该遵循的第一篇文章,我会告诉你为什么。

You should not follow the first article, and I will tell you why.

随着你的所有功能失去相当多的第一种​​方法该实体框架通过的DbContext提供,包括它的1级高速缓存,其身份地图,其单位的工作,其变化的跟踪和懒加载能力。这是因为在上面的场景中,为每个数据库查询创建和设置随即一个新的的DbContext 实例,从而防止的DbContext 例如从能够跟踪整个业务的交易数据对象的状态。

Following the first approach you're loosing pretty much every feature that Entity Framework provides via the DbContext, including its 1st-level cache, its identity map, its unit-of-work, and its change tracking and lazy-loading abilities. That's because in the scenario above, a new DbContext instance is created for every database query and disposed immediately afterwards, hence preventing the DbContext instance from being able to track the state of your data objects across the entire business transaction.

有一个的DbContext 如在你的仓库类中的私有财产也有它的问题。我认为更好的办法是有一个CustomDbContextScope。这种做法是很好的被这家伙解释说:迈赫迪萨尔瓦多Gueddari

Having a DbContext as a private property in your repository class also has its problems. I believe the better approach is having a CustomDbContextScope. This approach is very well explained by this guy: Mehdi El Gueddari

这文章的http://mehdi.me/ambient-dbcontext-in-ef6/ 是我见过有关的EntityFramework的最好的文章。你应该完全读它,我相信它会回答你所有的问题。

This article http://mehdi.me/ambient-dbcontext-in-ef6/ is the best article about EntityFramework I've ever seen. You should read it entirely, and I believe it will answer all your questions.

这篇关于C#中的实体框架:你的资料库类中正确使用的DbContext类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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