c# – 如何调用DbContext Threadsafe

我正在使用EF6,目前我偶尔会遇到错误;

Action Unhandled Exception: The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.

我已经阅读了关于herehere主题的几个有用的答案,我理解了出错的基本概念,但我不确定如何做出能够解决这个问题的改变.

我使用一个所有其他控制器继承的基本控制器类,我已经包含了下面的相关代码.我使用两个上下文,一个用于我的应用程序数据; DataModel,一个用于ASP NET Identity 2.0表; ApplicationDbContext.我认为每个新请求都会实例化一个新的基本控制器,因此新的上下文?

public class BaseController : Controller
{
    protected DataModel db = new DataModel();

    /// <summary>
    /// Application DB context
    /// </summary>
    protected ApplicationDbContext ApplicationDbContext { get; set; }

    /// <summary>
    /// User manager - attached to application DB context
    /// </summary>
    protected UserManager<ApplicationUser> UserManager { get; set; }

    public BaseController()
    {
        this.ApplicationDbContext = new ApplicationDbContext();
        this.UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.ApplicationDbContext));
        // We need to allow the user name to also be the email address
        UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager) { AllowOnlyAlphanumericUserNames = false };

        // Setup a token for Password Resets
        var provider = Startup.DataProtectionProvider;
        UserManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(provider.Create("UserToken"));
    }
}

关于我需要做出哪些改变的任何建议或例子将不胜感激.

解决方法

自定义属性/过滤器可能会导致并发问题.你的派生控制器中有没有?

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...