Skip to content

Instantly share code, notes, and snippets.

@TylerCarlson1
Created October 19, 2015 19:37
Show Gist options
  • Save TylerCarlson1/c12da95bf9cdd935b01b to your computer and use it in GitHub Desktop.
Save TylerCarlson1/c12da95bf9cdd935b01b to your computer and use it in GitHub Desktop.
EF 6 Delete Orphan Entities
public interface IDeleteOrphans
{
void DeleteOrphanedEntries();
}
public class DeleteOrphans<T> : IDeleteOrphans
where T : DbContext, IObjectContextAdapter
{
private readonly T _contextAdapter;
private readonly IList<PropertyInfo> _propertyInfos;
public DeleteOrphans(T contextAdapter)
{
_contextAdapter = contextAdapter;
var entitySets = _contextAdapter.ObjectContext.MetadataWorkspace.GetEntityContainer(contextAdapter.ObjectContext.DefaultContainerName, DataSpace.CSpace).EntitySets;
var typeAssemblies = Assembly.GetAssembly(contextAdapter.GetType()).GetTypes();
_propertyInfos = entitySets.SelectMany(es => GetNavigationProperties(es,typeAssemblies)).ToList();
}
private IEnumerable<PropertyInfo> GetNavigationProperties(EntitySet entitySet, Type[] typeAssemblies)
{
var type = typeAssemblies.First(t => t.Name == entitySet.ElementType.Name);
return entitySet.ElementType.DeclaredNavigationProperties.Select(p => type.GetProperty(p.Name)).ToList();
}
protected virtual IEnumerable<DbEntityEntry> OrphanedEntries
{
get { return _contextAdapter.ChangeTracker.Entries().Where(IsOrphaned).ToList(); }
}
private bool IsOrphaned(DbEntityEntry entity)
{
if (entity.State != EntityState.Modified)
return false;
return _propertyInfos.Where(p => p.DeclaringType.IsInstanceOfType(entity.Entity)).Any(p => p.GetValue(entity.Entity) == null);
}
public void DeleteOrphanedEntries()
{
foreach (var orphanedEntry in OrphanedEntries)
orphanedEntry.State = EntityState.Deleted;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment