Breeze 用于保存的 DbContext 中未启用延迟加载。原因详见this SO answer。
您应该在separate DbContext 中加载任何其他实体。
这是我在项目中如何做到这一点的示例。或许 MergeEntities 和 DetachEntities 方法应该包含在 Breeze 中,以便更简单地执行此操作。
protected override Dictionary<Type, List<EntityInfo>> BeforeSaveEntities(Dictionary<Type, List<EntityInfo>> saveMap)
{
// create a separate context for computation, so we don't pollute the main saving context
using (var newContext = new MyDbContext(EntityConnection, false))
{
var parentFromClient = (Parent)saveMap[typeof(Parent)][0].Entity;
// Load the necessary data into the newContext
var parentFromDb = newContext.Parents.Where(p => p.ParentId == parentFromClient.ParentId)
.Include("Children").ToList();
// ... load whatever else you need...
// Attach the client entities to the ObjectContext, which merges them and reconnects the navigation properties
var objectContext = ((IObjectContextAdapter)newContext).ObjectContext;
var objectStateEntries = MergeEntities(objectContext, saveMap);
// ... perform your business logic...
// Remove the entities from the second context, so they can be saved in the original context
DetachEntities(objectContext, saveMap);
}
return saveMap;
}
/// Attach the client entities to the ObjectContext, which merges them and reconnects the navigation properties
Dictionary<ObjectStateEntry, EntityInfo> MergeEntities(ObjectContext oc, Dictionary<Type, List<EntityInfo>> saveMap)
{
var oseEntityInfo = new Dictionary<ObjectStateEntry, EntityInfo>();
foreach (var type in saveMap.Keys)
{
var entitySet = this.GetEntitySetName(type);
foreach(var entityInfo in saveMap[type])
{
var entityKey = oc.CreateEntityKey(entitySet, entityInfo.Entity);
ObjectStateEntry ose;
if (oc.ObjectStateManager.TryGetObjectStateEntry(entityKey, out ose))
{
if (ose.State != System.Data.Entity.EntityState.Deleted)
ose.ApplyCurrentValues(entityInfo.Entity);
}
else
{
oc.AttachTo(entitySet, entityInfo.Entity);
ose = oc.ObjectStateManager.GetObjectStateEntry(entityKey);
}
if (entityInfo.EntityState == Breeze.ContextProvider.EntityState.Deleted)
{
ose.Delete();
}
oseEntityInfo.Add(ose, entityInfo);
}
}
return oseEntityInfo;
}
/// Remove the entities in saveMap from the ObjectContext; this separates their navigation properties
static void DetachEntities(ObjectContext oc, Dictionary<Type, List<EntityInfo>> saveMap)
{
foreach (var type in saveMap.Keys)
{
foreach (var entityInfo in saveMap[type])
{
try
{
oc.Detach(entityInfo.Entity);
}
catch
{ // the object cannot be detached because it is not attached
}
}
}
}