【发布时间】:2023-03-15 06:33:02
【问题描述】:
我有时会遇到这种奇怪的行为,当我尝试重新加载条目时:
DbEntityEntry<BatchServer> ent = d.Entry(jobServer);
//the ex is thrown at d.Entry
ent.Reload();
EF 抛出 NullReferenceException 异常。但是jobServer 和d(我的上下文变量)都不是空的,如果我们看看 StackTrace:
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Data.Objects.EntityEntry.DetectChangesInProperty(Int32 ordinal, Boolean detectOnlyComplexProperties, Boolean detectOnly)
at System.Data.Objects.EntityEntry.DetectChangesInProperties(Boolean detectOnlyComplexProperties)
at System.Data.Objects.ObjectStateManager.DetectChangesInScalarAndComplexProperties(IList`1 entries)
at System.Data.Objects.ObjectStateManager.DetectChanges()
at System.Data.Objects.ObjectContext.DetectChanges()
at System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean force)
at System.Data.Entity.Internal.InternalContext.GetStateEntry(Object entity)
at System.Data.Entity.Internal.InternalEntityEntry..ctor(InternalContext internalContext, Object entity)
at System.Data.Entity.DbContext.Entry[TEntity](TEntity entity)
at IEADPC.BatchRemoting.Monitor.ViewModel.MonitorViewModel.<>c__DisplayClass40.<>c__DisplayClass42.<RefreshAll>b__3d(BatchRemotingContexA first chance exception of type 'System.NullReferenceException' occurred in IEADPC.BatchRemoting.Monitor.dll
我们看到 EF 内部存在异常。这个错误是 100% 可重现的,但只有在程序中进行了大量工作之后。如果 EF 或我做错了什么,这是一个已知的错误吗?
问候
更新:
就在我调用它之前,我从上下文中获取所有服务器:
DataAccessObject.ClientDataAccess.WorkOnDatabase(d =>
{
var colzwei = new ObservableCollection<BatchServer>(d.BatchServers.ToList());
foreach (var jobServer in colzwei)
{
DbEntityEntry<BatchServer> ent;
ent = d.Entry(jobServer);
ent.Reload();
...
}
}
public void WorkOnDatabase(Action<BatchRemotingContext> databaseAction)
{
if (DbContext == null)
{
using (DbContext = ReturnDatabase())
{
databaseAction.Invoke(DbContext);
}
}
else
{
databaseAction.Invoke(DbContext);
}
}
这在整个程序中运行良好,只是当我在我的程序中工作时,有时会发生这种情况
【问题讨论】:
-
ent.Reload 是否发生异常? ent 是否为空?也许 jobServer 不再在数据库中?
-
什么是d。你设置了吗?
-
@tofutim 没有例外发生在
d.Entry(...)。ent.Reload();未被执行。 @Robuust 我做到了。我正在使用一个确保我始终使用有效连接的功能。这适用于所有其他情况。 -
您的
DbContext是BatchRemotingContext还是其他类? -
它是
BatchRemotingContext类。整个解决方案中没有其他上下文
标签: c# entity-framework