Skip to content

Instantly share code, notes, and snippets.

@afruzan
Created December 31, 2020 14:14
Show Gist options
  • Save afruzan/af8907d08c94e93875434b8ba09e1d33 to your computer and use it in GitHub Desktop.
Save afruzan/af8907d08c94e93875434b8ba09e1d33 to your computer and use it in GitHub Desktop.
private void sync<TEntity, TKey>(TEntity[] items, Func<TEntity, TKey> getId, TKey[] currentItemIds, out TKey[] keysToDelete, Action<TEntity> onAdd = null, Action<TEntity> onUpdate = null) where TEntity : class
{
foreach (var item in items)
{
if (currentItemIds.Contains(getId(item)))
{
_context.Entry(item).State = EntityState.Modified;
onUpdate?.Invoke(item);
}
else
{
_context.Entry(item).State = EntityState.Added;
onAdd?.Invoke(item);
}
}
keysToDelete = currentItemIds.Except(items.Select(i => getId(i))).ToArray();
}
private void sync_doDeletes<TEntity, TKey>(TKey[] keysToDelete, Action<TEntity> onDelete = null) where TEntity : class
{
foreach (var currentItemId in keysToDelete)
{
var item = _context.Set<TEntity>().Find(currentItemId);
//_context.Entry(item).State = EntityState.Deleted;
_context.Remove(item);
onDelete?.Invoke(item);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment