简体   繁体   中英

LINQ and EF6: The context cannot be used while the model is being created

I have an MVC 5 Application with EF6, and I tried my first LINQ query in a SignalR Hub. It runs when I click on a button on a Test view page.

But I get an exception at the query:

LINQ失败

This query is my first individual code action in the MVC5 template with individual User Accounts by the template. I only created the model classes before.

If it helps: The context I'm using is the template ApplicationDbContext:IdentityContext<ApplicationUser>

My "OnModelCreating" method looks like this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Entity<Player>()
            .HasMany(m => m.MilitaryAccess)
            .WithMany();
        modelBuilder.Entity<Player>()
            .HasMany(m => m.FactionRelationship)
            .WithMany();
        base.OnModelCreating(modelBuilder);}

Thank you in advance!

Could you try this and see if it helps

int result = -1;
using (var context = new ApplicationDbContext())
{
    var battles = context.Battles.Single(o =>o.BattleId == 1);
    result = battles.Round;
}
return result;

I had the exact same problem with EF6.1.1 and my solution to the problem was quite simple...

Change:

protected ApplicationDbContext db = new ApplicationDbContext();

To:

protected ApplicationDbContext Db {get; set;}

public TestHub()
{
  Db = new ApplicationDbContext();
}

But if you don't like this way, you can also use the LazySingleton Pattern approach.

Happy coding!

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