Last active
August 18, 2018 22:13
-
-
Save LSViana/40289068e4c1a56d68c7d991aa4b4a38 to your computer and use it in GitHub Desktop.
Updating Collections properly using EF Core
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Controller { | |
public IActionResult Put(Model posted) { | |
foreach (var item in fromDb.Collection) | |
{ | |
var editedItem = posted.Collection.FirstOrDefault(a => item.Id == a.Id); | |
if(editedItem is null) | |
Db.Remove(item); | |
else | |
Db.Entry(item).CurrentValues.SetValues(editedItem); | |
} | |
foreach (var item in post.Collection.Where(a => fromDb.Collection.All(b => b.Id != a.Id))) | |
{ | |
fromDb.Collection.Add(item); | |
Db.Add(item); | |
} | |
} | |
} | |
// Generic version to be used as extension method | |
public static void UpdateCollection<T>(this Controller controller, DbContext db, ICollection<T> fromDb, ICollection<T> posted, Func<T, T, bool> idSelector) where T : class | |
{ | |
foreach (var item in fromDb) | |
{ | |
var editedItem = posted.FirstOrDefault(a => idSelector(a, item)); | |
if (editedItem is null) | |
db.Remove(item); | |
else | |
db.Entry(item).CurrentValues.SetValues(editedItem); | |
} | |
foreach (var item in posted.Where(a => fromDb.All(b => !idSelector(a, b)))) | |
{ | |
fromDb.Add(item); | |
db.Add(item); | |
} | |
} | |
// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment