3

为什么会出现这个异常?这是一个错误吗?

我正在使用 Effort,EF 测试库来创建我的数据库的内存实例并遇到这个有趣的场景:

  1. 打开DbContext1
  2. 添加项目Table(不保存)
  3. DbContext1
  4. 打开DbContext2
  5. 计数项目Table

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

但是,如果我也在其中执行计数(步骤 5),DbContext1那么计数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)        
4

1 回答 1

1

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

    db.Database.CreateIfNotExists();

这对我有用。

于 2018-04-14T14:31:04.810 回答