Effort.Exceptions.EffortException:數據庫尚未初始化 - 非提交更新後?


為什麼會發生這種異常?這是一個錯誤嗎?

我正在使用Effort,EF測試庫來創建我的數據庫的內存實例,並遇到這個有趣的場景:

  1. 打開DbContext1
  2. 添加項目到Table (不保存)
  3. 關閉DbContext1
  4. 打開DbContext2
  5. 計算Table項目

Effort.Exceptions.EffortException : Database has not been initialized.

但是,如果我也在DbContext1執行計數(步驟5),那麼DbContext2中的Count不會失敗?

完整代碼

public void TestEF()
{
   var factory = new InMemoryMyApplicationDbContextFactory();

   using (var db = factory.CreateDbContext())
   {
      //uncomment this line to prevent exception - why????
      //db.Orders.Count();

      db.Orders.Add(new Order{ Id = Guid.NewGuid() }); 

      // intentionally do not call db.SaveChanges()
   }

   using (var db = factory.CreateDbContext())
   {
      // throws an exception if no read was performed above
      db.Orders.Count();
   }    
}    

完全例外:

public void TestEF()
{
   var factory = new InMemoryMyApplicationDbContextFactory();

   using (var db = factory.CreateDbContext())
   {
      //uncomment this line to prevent exception - why????
      //db.Orders.Count();

      db.Orders.Add(new Order{ Id = Guid.NewGuid() }); 

      // intentionally do not call db.SaveChanges()
   }

   using (var db = factory.CreateDbContext())
   {
      // throws an exception if no read was performed above
      db.Orders.Count();
   }    
}    

熱門答案

我接受了異常消息中提到的建議,並在using語句中將以下行添加到我的測試中

    db.Database.CreateIfNotExists();

這對我有用。





許可下: CC-BY-SA
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因