I'm using EF6 and currently I occasionally get an error;
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.
I have read through a couple of useful answer on the topic here and here and I understand the basic concept of what is going wrong, but I'm unsure about how exactly to make a change that will resolve this issue.
I use a Base Controller class that all other Controllers inherit from which I've included the relevant code for below. I use two Contexts, one for my application data; DataModel
, and one for the ASP NET Identity 2.0 tables; ApplicationDbContext
. I thought that each new request would instantiate a new Base Controller and therefore new Contexts?
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"));
}
}
Any advice or examples on what changes I need to make would be much appreciated.