0
\$\begingroup\$

I have an entity which has a list of other entities in it.

for example:

class Library
{
   public virtual List<Book> Books{get;set;}
}

And I would like to update the entity and also the list of entities inside.

I came up with this solution:

private void UpdateChild<T>(DbSet<T> dbset, ICollection<T> existingItems, ICollection<T> newItems, Func<T, T, bool> isEqual) where T : class
{
    dbset.RemoveRange(existingItems);

    foreach (var newItem in newItems)
    {
        T oldItem = existingItems.FirstOrDefault(x => isEqual(newItem, x));

        if (null != oldItem)
        {
            oldItem = newItem;

            dbset.Update(oldItem);
        }
        else
        {
            dbset.Add(newItem);
        }
    }
}

But I am not sure if this solution is a good approach.

\$\endgroup\$
  • \$\begingroup\$ Does this solution work? \$\endgroup\$ – t3chb0t Jun 17 at 15:55
  • \$\begingroup\$ Yes, But not tested carefully for every case. \$\endgroup\$ – Cami Jun 17 at 16:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.