我编写了一种方法来递归分离实体框架中的对象。实际上它是可行的,但问题是执行此方法后,一对多属性(对象的Collections)将被删除。在我的代码下方:
public void DetachRec(object objectToDetach)
{
DetachRec(objectToDetach, new HashSet<object>());
}
// context is my ObjectContext
private void DetachRec(object objectToDetach, HashSet<object> visitedObjects)
{
visitedObjects.Add(objectToDetach);
if (objectToDetach == null)
{
return;
}
Type type = objectToDetach.GetType();
PropertyInfo[] propertyInfos = type.GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
// on to many
if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>))
{
if (context.Entry(objectToDetach).Collection(propertyInfo.Name).IsLoaded)
{
var propValue = (IEnumerable) propertyInfo.GetValue(objectToDetach, null);
if (propValue != null)
{
var subcontext = new List<object>();
foreach (var subObject in propValue)
{
subcontext.Add(subObject);
}
foreach (var subObject in subcontext)
{
if (!visitedObjects.Contains(subObject))
{
context.DetachRecursive(subObject, visitedObjects);
}
}
}
}
}
// (many to one)
else if (propertyInfo.PropertyType.Assembly == type.Assembly)
{
//the part to detach many-to-one objects
}
}
context.Detach(objectToDetach);
}
最佳答案
在分离收集元素之前,您可以存储收集值并将收集属性设置为null
。这样,当元素和/或父实体分离时,您将防止EF删除集合元素。在该过程结束时,您只需将这些值恢复回来。
首先将以下using
添加到源代码文件:
using System.Data.Entity.Infrastructure;
更改公共方法的实现,如下所示:
public void DetachRec(object objectToDetach)
{
var visitedObjects = new HashSet<object>();
var collectionsToRestore = new List<Tuple<DbCollectionEntry, object>>();
DetachRec(objectToDetach, visitedObjects, collectionsToRestore);
foreach (var item in collectionsToRestore)
item.Item1.CurrentValue = item.Item2;
}
私有递归方法签名可以:
private void DetachRec(object objectToDetach, HashSet<object> visitedObjects, List<DbCollectionEntry, object>> collectionsToRestore)
一对多
if
块主体可以:var collectionEntry = context.Entry(objectToDetach).Collection(propertyInfo.Name);
if (collectionEntry.IsLoaded)
{
var collection = collectionEntry.CurrentValue;
if (collection != null)
{
collectionsToRestore.Add(Tuple.Create(collectionEntry, collection));
collectionEntry.CurrentValue = null;
foreach (var item in (IEnumerable)collection)
{
if (!visitedObjects.Contains(item))
{
DetachRec(item, visitedObjects, collectionsToRestore);
}
}
}
}
到此为止。
关于c# - Entity Framework 中的递归实体分离,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43146332/