微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

解决方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐