为什么会发生此异常?这是错误吗?

我正在使用EF测试库Effort创建数据库的内存中实例,并遇到以下有趣的情况:


打开DbContext1
将项目添加到Table(不保存)
关闭DbContext1
打开DbContext2
计算Table中的项目


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

但是,如果我也在DbContext1中执行计数(第5步),那么DbContext2中的计数不会失败?

完整代码:

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


完全例外:

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

If using CodeFirst try to add the following line:
   context.Database.CreateIfNotExists()
 at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
 at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
 at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
 at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
 at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
 at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
 at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
 at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)

最佳答案

我接受了异常消息中提到的建议,并在using语句中的测试中添加了以下行

    db.Database.CreateIfNotExists();


那对我有用。

关于c# - Effort.Exceptions.EffortException:数据库尚未初始化-未提交更新后?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46135973/

10-11 04:00