gpt4 book ai didi

c# - "Context cannot be used while the model is being created"异常与 ASP.NET 标识

转载 作者:IT王子 更新时间:2023-10-29 03:55:38 26 4
gpt4 key购买 nike

为什么当我们调用 AccountApiController.Register() 方法时会发生这种情况?

  • 什么试图使用上下文?
  • 什么试图创建上下文?
  • 我们如何避免这种情况?
  • 我们如何调试它?

"Message":"An error has occurred.",

"ExceptionMessage":"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.",

"ExceptionType":"System.InvalidOperationException",

"StackTrace":"

at System.Web.Http.ApiController.d__1.MoveNext()

--- End of stack trace from previous location where exception was thrown

at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

at System.Runtime.CompilerServices.TaskAwaiter .HandleNonSuccessAndDebuggerNotification(Task > task)

at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__0.MoveNext()"

最佳答案

问题是我们没有使用工厂模式 MS recommends .

You can use Factory implementation to get an instance of UserManager from the OWIN context. ... This is a recommended way of getting an instance of UserManager per request for the application.

因此,“多个线程同时访问同一个上下文实例”,因为多个请求和线程共享一个 DbContext。

以下是正确的。它为每次调用 UserManagerFactory 函数创建一个新的 MyDbContext 实例。

UserManagerFactory 
= () => new UserManager<IdentityUser>(new UserStore<IdentityUser>(new MyDbContext()));

以下是不正确的。它看起来很相似,但不会为每次调用 UserManagerFactory 创建一个新实例。这是我们正在使用的,因此我们的网站坏了。

var userStore = new UserStore<IdentityUser>(new MyDbContext());                    
var userManager = new UserManager<IdentityUser>(userStore);
UserManagerFactory = () => userManager;

关于c# - "Context cannot be used while the model is being created"异常与 ASP.NET 标识,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21344232/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com