Skip to content

Instantly share code, notes, and snippets.

@RodH257
Last active Dec 10, 2015
Embed
What would you like to do?
EF Detatch
static int[] Detach<TEntity>(
this IUnitOfWork unitOfWork, Func<TEntity, bool> where, Func<TEntity, int> getKey = null)
where TEntity : EntityObject
{
if (!(unitOfWork is ObjectContext))
{
return new int[0];
}
var objectContext = ((ObjectContext)unitOfWork);
var objectStateManager = objectContext.ObjectStateManager;
var entitiesToDetach = objectStateManager
.GetObjectStateEntries(EntityState.Modified | EntityState.Unchanged | EntityState.Deleted)
.Where(entry => entry.Entity != null && entry.Entity.GetType() == typeof(TEntity) && @where((TEntity)entry.Entity))
.Select(entry => (TEntity)entry.Entity)
.ToList();
foreach (var entity in entitiesToDetach)
{
objectContext.Detach(entity);
}
if (getKey == null)
{
return new int[0];
}
return entitiesToDetach.Select(entity => getKey(entity)).ToArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment