加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何调用DbContext Threadsafe

发布时间:2020-12-15 20:54:06 所属栏目:百科 来源:网络整理
导读:我正在使用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 insta
我正在使用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.

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

我使用一个所有其他控制器继承的基本控制器类,我已经包含了下面的相关代码.我使用两个上下文,一个用于我的应用程序数据; 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"));
    }
}

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

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读