当我应该创建一个新的DbContext() [英] When should I create a new DbContext()

查看:358
本文介绍了当我应该创建一个新的DbContext()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前使用的是的DbContext 与此类似:

 命名空间模型
{
    公共类ContextDB:的DbContext
    {        公共DbSet<使用者>用户{搞定;组; }
        公共DbSet<&UserRole的GT; {的UserRole获取;组; }        公共ContextDB()
        {        }
    }
}

我使用,然后在全部我的控制器,需要访问数据库的顶部到下一行。林还用它在我的UserRepository类,它包含与用户的所有方法(如获取活动的用户,检查什么样的角色他,等..):

  ContextDB _db =新ContextDB();

想到这些。还有occations当一个访问者可以有多个DbContexts活跃..即。如果HES访问使用该UserRepository控制器..这可能不是最好的想法,我有一个关于它的几个问题。


  1. 我什么时候应该做一个新的DbContext /我应该有一个全球的背景下,我绕过?

  2. 我可以有一个全局背景下,我在所有的地方重用?

  3. 这是否会导致性能的下降?

  4. 如何其他人这样做呢?


解决方案

我使用一个基控制器,它暴露了一个数据库导出控制器可以访问属性。

 公共抽象类BaseController:控制器
{
    公共BaseController()
    {
        数据库=新DatabaseContext();
    }    保护DatabaseContext数据库{搞定;组; }    保护覆盖无效的Dispose(BOOL处置)
    {
        Database.Dispose();
        base.Dispose(处置);
    }
}

在我的应用程序控制器,从 BaseController 派生并使用这样的:

 公共类UserController的:BaseController
{
    [HTTPGET]
    公众的ActionResult指数()
    {
        返回查看(Database.Users.OrderBy(P => p.Name).ToList());
    }
}

现在回答你的问题:


  

我什么时候应该做一个新的DbContext /我应该有一个全球范围内的
  我绕过?


上下文应该按要求设立。创建的背景下,你需要做什么用的它,然后摆脱它。与基类解决方案,我用你只需要担心使用的上下文。

不要尝试,有一个全球范围内(这是不是Web应用程序是如何工作的)。


  

我可以有一个全球背景下,我在所有的地方重用?


没有,如果你保持一个背景下围绕它会跟踪所有的更新,添加,删除等,这将放慢您的应用程序,甚至可能导致某些pretty微妙的错误出现在你的应用程序。

您或许应该选择要么暴露你的资料库您的语境下,以你的控制器,但不能同时使用。有两个背景是从同样的方法访问会导致错误,如果他们都对应用程序的当前状态不同的想法。

我个人preFER揭露的DbContext 直接作为最库的例子我见过只是结束了各地的的DbContext 反正。


  

这是否会导致性能的下降?


第一次的DbContext 创建为pretty昂贵的,但一旦这个已经做了很多的信息被缓存,以便后续实例是快了很多。你更可能看到各地保持环境比你从实例每次需要访问数据库一次一个性能问题。


  

如何其他人这样做呢?


这要看情况。

有人preFER使用依赖注入框架创建时其上下文的具体实例传递给他们的控制器。这两个选项都很好。我的是更适合在您知道所使用的特定的数据库是不会改变的一个小规模的应用。

有些人可能会认为,你的无法的知道这一点,这就是为什么依赖注入的方法更好,因为它使你的应用程序更适应变化。我对这个问题的看法是,它可能不会改变(SQL服务器和放大器;实体框架是很难模糊),我的时间最好花在写code特定于我的应用程序

I am currently using a DbContext similar to this:

namespace Models
{
    public class ContextDB: DbContext
    {

        public DbSet<User> Users { get; set; }
        public DbSet<UserRole> UserRoles { get; set; }

        public ContextDB()
        {

        }
    }
}

I am then using the following line at the top of ALL my controllers that need access to the database. Im also using it in my UserRepository Class which contains all methods relating to the user (such as getting the active user, checking what roles he has, etc..):

ContextDB _db = new ContextDB();

Thinking about this.. there are occations when one visitor can have multiple DbContexts active.. ie. if hes visiting a controller that uses the UserRepository.. this might not be the best of ideas, and I've got a few questions about it

  1. When should I make a new DbContext / should I have one global context that I pass around?
  2. Can i have one global Context that I reuse in all places?
  3. Does this cause a performance hit?
  4. How is everyone else doing this?

解决方案

I use a base controller that exposes a DataBase property that derived controllers can access.

public abstract class BaseController : Controller
{
    public BaseController()
    {
        Database = new DatabaseContext();
    }

    protected DatabaseContext Database { get; set; }

    protected override void Dispose(bool disposing)
    {
        Database.Dispose();
        base.Dispose(disposing);
    }
}

All of the controllers in my application derive from BaseController and are used like this:

public class UserController : BaseController
{
    [HttpGet]
    public ActionResult Index()
    {
        return View(Database.Users.OrderBy(p => p.Name).ToList());
    }
}

Now to answer your questions:

When should I make a new DbContext / should I have one global context that I pass around?

The context should be created per request. Create the context, do what you need to do with it then get rid of it. With the base class solution I use you only have to worry about using the context.

Do not try and have a global context (this is not how web applications work).

Can I have one global Context that I reuse in all places?

No, if you keep a context around it will keep track of all the updates, additions, deletes etc and this will slow your application down and may even cause some pretty subtle bugs to appear in your application.

You should probably chose to either expose your repository or your Context to your controller but not both. Having two contexts being access from the same method is going to lead to bugs if they both have different ideas about the current state of the application.

Personally, I prefer to expose DbContext directly as most repository examples I have seen simply end up as thin wrappers around DbContext anyway.

Does this cause a performance hit?

The first time a DbContext is created is pretty expensive but once this has been done a lot of the information is cached so that subsequent instantiations are a lot quicker. you are more likely to see performance problems from keeping a context around than you are from instantiating one each time you need access to your database.

How is everyone else doing this?

It depends.

Some people prefer to use a dependency injection framework to pass a concrete instance of their context to their controller when it is created. Both options are fine. Mine is more suitable for a small scale application where you know the specific database being used isn't going to change.

some may argue that you can't know this and that is why the dependency injection method is better as it makes your application more resilient to change. My opinion on this is that it probably won't change (SQL server & Entity Framework are hardly obscure) and that my time is best spent writing the code that is specific to my application.

这篇关于当我应该创建一个新的DbContext()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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