简体   繁体   中英

Two different instances of my dbcontext in EF are colliding with “The context cannot be used while the model is being created.”

I have a WebAPI solution with an endpoint "DeleteFolder". That looks like this:

    public FolderController()
    {
        _service = new DtoService();
    }
    [HttpDelete]
    public HttpResponseMessage DeleteFolder(int id)
    {
        _service.DeleteFolder(id);
        return Request.CreateResponse(HttpStatusCode.OK, "Deleted");
    }

My _service is an instance of DtoService.cs which contains this:

    public DtoService()
    {
        _repository = new RepositoryService();
    }
    public void DeleteFolder(int folderId)
    {
        _repository.DeleteFolder(folderId);
    }

Finally, in my repository I have this:

    public RepositoryService()
    {
        _db = new AppDbContext();
    }
    public void DeleteFolder(int folderId)
    {
     var folder = GetFolder(folderId);
     _db.Folders.Remove(folder);
     SaveChanges();
    }

Where _db is an instance of my project's DbContext, defined once in the constructor of the Repository class.

When I send a bunch of asynchronous AJAX calls to the delete method, I get "The context cannot be used while the model is being created.". I can see a new instance of RepositoryService spinning up for each one, but if I set a breakpoint at

var folder = GetFolder(folderId);

and then step over, it's hit again, so it seems the other instance is trying to hit the same code before the first one completes, which is somehow causing this error to be thrown.

I don't have any references to my dbContext in my WebAPI layer or DTO service layer - and I'd prefer to keep it that way if possible. I tried wrapping the DeleteFolder code in a using (_db = new AppDbContext) but this didn't work either - and I feel like peppering all of my repository methods with a new dbcontext can't possibly be a recommended solution.

What's going on here? Any tips would be awesome, I'm totally at a loss here.

One thread is initializing your context in response to a request (it's a lengthy process), and another comes in attempting to use the context. The second request thinks the context is ready for use and you get this exception: “The context cannot be used while the model is being created.” The following code shows how to force database initialization in EF Code First at start up:

protected void Application_Start() {
     // ... 

     // Initializes and seeds the database.
     Database.SetInitializer(new MyDBInitializer());
 
     // Forces initialization of database on model changes.
     using (var context = new ApplicationDB()) {
          context.Database.Initialize(force: true);
     }

     // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM