Skip to content

Instantly share code, notes, and snippets.

@RodH257
Last active December 10, 2015 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RodH257/4472165 to your computer and use it in GitHub Desktop.
Save RodH257/4472165 to your computer and use it in GitHub Desktop.
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