0

I am running Entity Framework Core with a Blazor WASM Hosted Solution. I have a model that is like follows:

public class Parent
{
    public int ParentID { get; set; }
    public List<Child> Children { get; set; }
}

The Client Side Blazor is getting the Parent object via an API call, the List is being modified to add/remove items from its list, then being sent back to the API for an Update/Save.

public async Task UpdateAsync(int id, Parent Parent)
        {
            try
            {
                if (!await ExistsAsync(id))
                    return;

                _dataContext.Entry(Parent).State = EntityState.Modified;
                await _dataContext.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error in UpdateAsync()");
                throw;
            }
        }

The Code above does not update the collection of the Child so the next time the Get is called its as it was before the update. After doing some research I can see that EF cannot track the changes if the object is being serialized and deserialized via an API. I tried the following

public async Task UpdateAsync(int id, Parent Parent)
        {
            try
            {
                if (!await ExistsAsync(id))
                    return;

                //_dataContext.Entry(Parent).State = EntityState.Modified;
                _dataContext.Parents.Update(Parent);
                await _dataContext.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error in UpdateAsync()");
                throw;
            }
        }

With this change I am able to Add new items to the collection and it saves correctly, however removing items from the collection do not work.

I have found this answer which Manually tracks the addition and removal of child properties but this was over 6yrs ago. I was hoping that EF had changed since then to possibly support this.

How to add/update child entities when updating a parent entity in EF

JoeyD
  • 446
  • 3
  • 15
  • Removing elements in EF is not the same as Adding/Editing, you must call `Parent.Children.Remove(Child)` for the removal to work correctly. – Cory Podojil May 18 '21 at 15:45
  • In that case i would have to manually track what Children were and what Children are now. I am trying to see if there is a more elegant solution than the link I had provided that did the manual tracking – JoeyD May 18 '21 at 16:39
  • Hm, not sure why you are concerned with this. You don't have a choice as that's literally how EF works: https://www.learnentityframeworkcore.com/dbset/deleting-data#related-data – Cory Podojil May 18 '21 at 18:30

0 Answers0