// merge all dependent relationships from a given source object to a destination object, then optionally remove the source // accepts a source and destination entity of the same type, as well as an optionally specified list of relationship names and an optional flag to preserve the source object public static void Merge <T>(DbContext context, T source, T destination, List <string> relationshipsToMerge = null, bool preserveSource = false) { if (relationshipsToMerge == null) { relationshipsToMerge = EntityOperations.GetDependentPropertyInfo(source); // grab all dependent relationships if not explicitly specified } foreach (var relationship in relationshipsToMerge) { var collection = EntityOperations.ResolveRelationship(context, source, relationship); if (collection == null) { continue; // relationship doesn't exist, skip } foreach (var dependent in EntityOperations.ExtractToList((IEnumerable)collection.CurrentValue)) { context.Entry(dependent).Reference(source.GetType().Name).CurrentValue = destination; // remap each dependent entity to destination object } } if (!preserveSource) { EntityOperations.Delete(context, source); // remove source object and unmerged dependencies } context.SaveChanges(); }
// delete entity and dependent relationships public static void Delete(DbContext context, object entity) { var relationshipsToDelete = EntityOperations.GetDependentPropertyInfo(entity); // grab all dependent relationships foreach (var relationship in relationshipsToDelete) { var collection = EntityOperations.ResolveRelationship(context, entity, relationship); if (collection == null) { continue; // relationship doesn't exist, skip } foreach (var dependent in EntityOperations.ExtractToList((IEnumerable)collection.CurrentValue)) { context.Entry(dependent).State = EntityState.Deleted; // remove dependent entity } } context.Entry(entity).State = EntityState.Deleted; // remove original entity }