我一直试图将一些EF6代码重构为EF Core 1并且遇到了一个小绊脚石。我试图转换的代码在这里:
https://github.com/mehdime/DbContextScope
一切都很好,但特别是DbContextScope.cs证明是棘手的,例如这个方法(为简洁起见):
public void RefreshEntitiesInParentScope(IEnumerable entities)
{
foreach (IObjectContextAdapter contextInCurrentScope in
_dbContexts.InitializedDbContexts.Values)
{
var correspondingParentContext =
_parentScope._dbContexts.InitializedDbContexts.Values
.SingleOrDefault(parentContext =>
parentContext.GetType() == contextInCurrentScope.GetType())
as IObjectContextAdapter;
if (correspondingParentContext == null)
continue;
foreach (var toRefresh in entities)
{
ObjectStateEntry stateInCurrentScope;
if (contextInCurrentScope.ObjectContext.ObjectStateManager
.TryGetObjectStateEntry(toRefresh, out stateInCurrentScope))
{
var key = stateInCurrentScope.EntityKey;
ObjectStateEntry stateInParentScope;
if (correspondingParentContext.ObjectContext.ObjectStateManager
.TryGetObjectStateEntry(key, out stateInParentScope))
{
if (stateInParentScope.State == EntityState.Unchanged)
{
correspondingParentContext.ObjectContext.Refresh(
RefreshMode.StoreWins, stateInParentScope.Entity);
}
}
}
}
}
}
问题。
首先,我知道我可以用新的ChangeTracker替换ObjectContext.ObjectStateManager但是要确保我获得的条目是正确获取的。如何在EF Core中翻译以下行?
contextInCurrentScope.ObjectContext.ObjectStateManager
.TryGetObjectStateEntry(toRefresh, out stateInCurrentScope)
其次,在EF Core中这相当于什么?
correspondingParentContext.ObjectContext.Refresh
谢谢!
P.S。上面的GitHub回购源中有很多有用的评论。
答案 0 :(得分:1)
我认为获取实体条目(因此是键和状态)的正确方法是:
var entry = contextInCurrentScope.Entry(toRefresh);
var keys = entry.Metadata.GetKeys();
var state = entry.State;
您还可以使用以下条目从数据库刷新单个实体:
entry.Reload();