【发布时间】:2016-11-21 15:40:38
【问题描述】:
我一直在尝试将一些 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 中的 this 等价物是什么?
correspondingParentContext.ObjectContext.Refresh
谢谢!
附:上面的 GitHub repo 的源代码中有很多有用的 cmets。
【问题讨论】:
标签: c# entity-framework entity-framework-6 entity-framework-core