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

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

问题描述

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

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

然后我在需要访问数据库的ALL控制器顶部使用以下行.我也在我的 UserRepository 类中使​​用它,其中包含与用户相关的所有方法(例如获取活动用户、检查他拥有的角色等):

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

考虑到这一点,有时一个访问者可以有多个 DbContext 处于活动状态,例如,如果它正在访问使用 UserRepository 的控制器,这可能不是最好的想法.

Thinking about this, there are occasions when one visitor can have multiple DbContexts active, for instance if it is visiting a controller that uses the UserRepository, which might not be the best of ideas.

我应该什么时候创建一个新的 DbContext?或者,我应该有一个在所有地方传递并重用的全局上下文吗?这会导致性能下降吗?也欢迎提出替代方法的建议.

When should I make a new DbContext? Alternatively, should I have one global context that is passed around and reused in all places? Would that cause a performance hit? Suggestions of alternative ways of doing this are also welcome.

推荐答案

我使用一个基础控制器,它公开了一个派生控制器可以访问的 DataBase 属性.

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

我的应用程序中的所有控制器都派生自 BaseController 并像这样使用:

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

现在回答您的问题:

我什么时候应该创建一个新的 DbContext/我应该有一个全局上下文我路过?

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.

就我个人而言,我更喜欢直接公开 DbContext,因为我见过的大多数存储库示例最终都只是作为 DbContext 的薄包装器.

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

这会导致性能下降吗?

第一次创建 DbContext 的开销非常大,但是一旦创建完成,就会缓存大量信息,以便后续实例化更快.与每次需要访问数据库时实例化上下文相比,保持上下文更可能导致性能问题.

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?

这取决于.

有些人更喜欢使用依赖注入框架在创建时将其上下文的具体实例传递给控制器​​.这两个选项都不错.我的更适合小型应用程序,您知道正在使用的特定数据库不会改变.

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.

有些人可能会争辩说您不能知道这一点,这就是为什么依赖注入方法更好,因为它使您的应用程序更能适应变化.我对此的看法是它可能不会改变(SQL 服务器和实体框架几乎没有什么晦涩难懂)并且我的时间最好花在编写特定于我的应用程序的代码上.

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天全站免登陆