Home > Enterprise >  Ef6 deleting child from parent's children collection doesn't work
Ef6 deleting child from parent's children collection doesn't work

Time:10-17

I try to delete child entity by removing it from parent children collection, but after doing that ChangeTracker marks child entity as Modified so the entity isn't deleted from database (moreover it continues to be 'modified' even after SaveChanges). It's weird because when I use the same trick to add child it works fine.

I don't delete/add entity using DbContext, because I want to have discard changes logic. When I start to modify object I remember its state, discarding changes reverts properties and children collections to remembered state, applying changes updates remembered state.

So why does adding new child work, but deleting child doesn't, and why does deleted entry is marked as modified in the ChangeTracker?

class Parent
{
    public int Id { get; set; }
    public ICollection<Child> Children { get; set; }
}

class Child
{
    public int Id { get; set; }
    public int ParentId { get; set; }
    public Parent Parent { get; set; }
}

class MyContext : DbContext
{
    ...
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Child>()
            .HasRequired<Parent>(c => c.Parent)
            .WithMany(p => p.Children)
            .HasForeignKey(c => c.ParentId);
    }
}

class MyClass
{
    private MyContext context;    

    public Parent Parent { get; set; }
    ...
    
    public void DeleteChild(Child child)
    {
        Parent.Children.Remove(child);// doesn't work
        context.SaveChanges();
    }

    public void AddChild(Child child)
    {
        Parent.Children.Add(child);// works
        context.SaveChanges();
    }
}

CodePudding user response:

I found answer there

You aren't deleting the object with the remove statement. Instead you are attempting to alter a record and make it an orphan (by setting the foreign key to null). The database has a non-null constraint on that column and prevents you from doing so.

  • Related