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