Ich habe eine Methode zum rekursiven Lösen meiner Objekte im Entity Framework geschrieben. Eigentlich funktioniert es, aber das Problem ist, nach dem Ausführen dieser Methode, die eins zu viele Eigenschaften (die Sammlungen des Objekts) entfernt werden. Im Folgenden mein Code:Rekursive Entity im Entity Framework loslösen
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);
}
Wenn Sie sagen, die Sammlungen "sind entfernt", was bedeutet das? Bedeutet das, dass die Eigenschaft null zurückgibt? – JuanR
Bitte lesen Sie http://stackoverflow.com/a/7693732/430661 und prüfen Sie, ob es zutrifft. –
@Juan, ja es bedeutet, die Eigenschaft gibt null zurück. –