簡體   English   中英

LINQ和EF6:創建模型時無法使用上下文

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

我有一個帶有EF6的MVC 5應用程序,我在SignalR集線器中嘗試了我的第一個LINQ查詢。 當我單擊“測試”視圖頁面上的按鈕時,它將運行。

但是我在查詢中遇到異常:

LINQ失敗

該查詢是我在MVC5模板中的第一個單獨的代碼操作,其中包含模板中的各個用戶帳戶。 我以前只是創建模型類。

如果有幫助:我正在使用的上下文是模板ApplicationDbContext:IdentityContext<ApplicationUser>

我的“ OnModelCreating”方法如下所示:

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);}

先感謝您!

您可以嘗試一下,看看是否有幫助

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

我在EF6.1.1中遇到了完全相同的問題,而我對該問題的解決方案非常簡單...

更改:

protected ApplicationDbContext db = new ApplicationDbContext();

至:

protected ApplicationDbContext Db {get; set;}

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

但是,如果您不喜歡這種方式,也可以使用LazySingleton模式方法。

編碼愉快!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM