Search code examples
c#entity-frameworkasp.net-web-apiblazorentity

Options to Delete Entity child from children when deleted in parent object


I have the following classes

{
    public int Id { get; set; }
    public string Name { get; set; }
    public IEnumerable<Child> Children { get; set; }
}

public class Child
{
    public int Id { get; set; }
    publict int ParentId {get; set;}
    public string ChildName { get; set; }
}

In the blazor frontend the parent object is changed and some children are deleted. first get parent include childs:

  • Parent.where(id==id).include(children); (kind of)

then delete & update childs in edit form

  • Parent.Children.remove(id==id)

submit form and send Parent object to db for storage:

After:

ctx.update(parent);
ctx.savechanges();

The children are updated but the deleted children are still in the DB.
Is the only option to remove the deleted children, to get the existing children from the DB where parentId == ParentId and compare them with the updated children?


Solution

  • First try using

    ICollection<Child> Children 
    

    instead of using

    IEnumerable<Child> Children
    

    then try to remove the child object(debug to validate) from the parent object, then call ctx.Update(parent) method(I assume this is not tracked)

    Example:

    @page "/"
    @inject ParentChildContext context
    <h1>Hello, world!</h1>
    
    Welcome to your new app.
    
    <SurveyPrompt Title="How is Blazor working for you?" />
    <button @onclick="@(() => DeleteChild())">Click me</button>
    @code {
        Parent parent;
    
        protected async override Task OnAfterRenderAsync(bool firstRender)
        {
            if(firstRender)
            {
                parent = new Parent()
                {
                    Id = 1,
                    Name = "Parent 1",
                    Children = new List<Child>() {
                    new Child() { Id = 1, Name = "ChildName" },
                    new Child() { Id = 2, Name = "ChildName2" }
                }
    
                };
                context.Parents.Add(parent);
    
                await context.SaveChangesAsync();
            }
    
        }
    
        private async void DeleteChild()
        {
            parent.Children.Remove(parent.Children.ToList().FirstOrDefault(x => x.Id == 1));        
            context.SaveChanges();
        }
    }