Skip to content

Instantly share code, notes, and snippets.

@PBeckerr
Last active January 16, 2019 22:49
Show Gist options
  • Save PBeckerr/9226395766143048be6e85df4e8e1f24 to your computer and use it in GitHub Desktop.
Save PBeckerr/9226395766143048be6e85df4e8e1f24 to your computer and use it in GitHub Desktop.
public static class DbContextExtensions
{
/// <summary>
/// Add, update or delete a nested property list regardless of enabled auto changetracking
/// </summary>
/// <typeparam name="TSourceListEntry">Type of sourcelist like XXViewModel</typeparam>
/// <typeparam name="TTargetListEntry">Type of targetlist like DbModel</typeparam>
/// <typeparam name="TKey">Type of key</typeparam>
/// <param name="context"></param>
/// <param name="oldValues">List of dbmodels</param>
/// <param name="newValues">List of dtoModels</param>
/// <param name="sourceEqualProperty"></param>
/// <param name="targetEqualProperty"></param>
public static void AddOrUpdateOrDeleteList<TSourceListEntry, TTargetListEntry, TKey>(
this DbContext context,
ICollection<TTargetListEntry> oldValues,
ICollection<TSourceListEntry> newValues,
Func<TSourceListEntry, TKey> sourceEqualProperty,
Func<TTargetListEntry, TKey> targetEqualProperty)
{
List<TTargetListEntry> newEntries = new List<TTargetListEntry>();
ICollection<TTargetListEntry> targetList = oldValues;
//Check for updates
foreach (TTargetListEntry targetListEntry in targetList)
{
bool stillExists = false;
foreach (TSourceListEntry sourceListEntry in newValues)
{
if (targetEqualProperty(targetListEntry).Equals(sourceEqualProperty(sourceListEntry)))
{
//update
Mapper.Map(sourceListEntry, targetListEntry);
context.Entry(targetListEntry).State = EntityState.Modified;
stillExists = true;
}
}
if (!stillExists)
{
context.Entry(targetListEntry).State = EntityState.Deleted;
}
}
//Check for new entries
foreach (TSourceListEntry newValue in newValues)
{
bool oldValueFound = false;
foreach (TTargetListEntry oldValue in targetList)
{
if (targetEqualProperty(oldValue).Equals(sourceEqualProperty(newValue)))
{
oldValueFound = true;
break;
}
}
if (!oldValueFound)
{
newEntries.Add(Mapper.Map<TTargetListEntry>(newValue));
}
}
foreach (TTargetListEntry targetListEntry in newEntries)
{
//add to target and update changetracking
targetList.Add(targetListEntry);
context.Entry(targetListEntry).State = EntityState.Added;
}
}
}
@PBeckerr
Copy link
Author

Not tested, just straight outta ma head 💯

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment