【问题标题】:LINQ and EF6: The context cannot be used while the model is being createdLINQ 和 EF6:创建模型时无法使用上下文
【发布时间】:2014-06-11 02:45:50
【问题描述】:

我有一个带有 EF6 的 MVC 5 应用程序,我在 SignalR Hub 中尝试了我的第一个 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);}

提前谢谢你!

【问题讨论】:

  • 您认为多线程是问题所在,但您没有显示任何使用多线程的代码。
  • OnModelCreating 在哪里运行?
  • 是的,我“认为”,我对 MVC/EF 的工作原理没有任何经验。我刚刚创建了一些模型类。其余的仍然来自模板。上面显示的代码是我的第一个单独的代码操作。
  • @PeterSmith 它在提到的“ApplicationDbContext”类中运行。
  • 该错误实际上是不言自明的,您正在尝试在实际构建之前对其进行上下文。我的猜测是您的代码在 beforeduring 触发 OnModelCreating 事件时运行 - 使用调试器并在代码的每个部分放置一个断点,您想要点击OnModelCreating 在您拨打 GetDBData 电话之前,如果您不这样做,那就是您的问题。 GetDBData 到底是在哪里调用的?这就是问题的根源......

标签: c# asp.net-mvc linq entity-framework entity-framework-6


【解决方案1】:

你可以试试这个,看看是否有帮助

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

【讨论】:

    【解决方案2】:

    我在使用 EF6.1.1 时遇到了完全相同的问题,我的解决方案非常简单...

    变化:

    protected ApplicationDbContext db = new ApplicationDbContext();
    

    收件人:

    protected ApplicationDbContext Db {get; set;}
    
    public TestHub()
    {
      Db = new ApplicationDbContext();
    }
    

    但是如果你不喜欢这种方式,你也可以使用 LazySingleton Pattern 的方式。

    编码愉快!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-30
      • 1970-01-01
      • 2016-01-13
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      相关资源
      最近更新 更多