I'm trying to do a generic method to update Entity Framework collections, one to many. I did this method, but i'm having a problem, when i try to verify, if the element in the new collection already exists in the old one. If exists, i have to update it, rather then remove and add it again.
The code is this:
public TEntity UpdateCollection<TEntity, TChildren>(myappContext dbContext, TEntity parentObject, Expression<Func<TEntity,
ICollection<TChildren>>> propertyExpression, ICollection<TChildren> objectChilren) where TEntity : class where TChildren : class
{
var parentEntityObject = dbContext.Entry<TEntity>(parentObject);
List<TChildren> originalChildrenData = parentEntityObject.Collection(propertyExpression).CurrentValue.ToList();
// Updating or removing existing items
foreach (var originalItem in originalChildrenData)
{
// Where the problem is: If entry was just modified, i have to update.
var newItem = objectChilren.FirstOrDefault(x => x == originalItem);
if (newItem != null)
{
dbContext.Entry<TChildren>(originalItem).CurrentValues.SetValues(newItem);
dbContext.Entry<TChildren>(originalItem).State = System.Data.EntityState.Modified;
}
else
{
dbContext.Entry<TChildren>(originalItem).State = System.Data.EntityState.Deleted;
}
}
// Adding new items
foreach(var newItem in objectChilren.Except(originalChildrenData)){
parentEntityObject.Collection(propertyExpression).CurrentValue.Add(newItem);
}
parentEntityObject.State = System.Data.EntityState.Modified;
return parentEntityObject.Entity;
}
Instead of try to check with:
var newItem = objectChilren.FirstOrDefault(x => x == originalItem);
if (newItem != null)
I also tryed with:
var newItem = this.Set<TChildren>().Local.FirstOrDefault(x => x == originalItem);
But also doesn't work, always returns null. I have to get the corresponding entry and only update it.
If it's not possible, there is another generic way to update collections "one to many"?