gpt4 book ai didi

c# - 努力.Exceptions.EffortException : Database has not been initialized - after non commited update?

转载 作者:行者123 更新时间:2023-11-30 17:32:43 24 4
gpt4 key购买 nike

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

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

  1. 打开DbContext1
  2. 将项目添加到(不保存)
  3. 关闭DbContext1
  4. 打开DbContext2
  5. 计算中的项目数

Effort.Exceptions.EffortException:数据库尚未初始化。

但是,如果我也在 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# - 努力.Exceptions.EffortException : Database has not been initialized - after non commited update?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46135973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com