1
我已經寫了一個遞歸分離實體框架中的對象的方法。實際上它可以工作,但問題是,在執行此方法後,將刪除一對多屬性(對象的集合)。下面我的代碼:實體框架中的遞歸實體分離
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? – JuanR
請閱讀http://stackoverflow.com/a/7693732/430661,看看它是否適用。 –
@Juan,是的,這意味着,該屬性返回null。 –