Search code examples
c#entity-frameworkcollectionsef-model-builder

Delete List of entities of the same entity on update


Hello everyone I can't find a solution to this problem, I have an Entity that have a property created like this on DbModelBuilder

First a class with a property RelatedFoo which is a list to the same Foo Entity

public class Foo
    {
        public int FooId { get; set; }
        public string Name { get; set; }

        public virtual List<Foo> RelatedFoo { get; set; }
    }

This was created in DbContext

modelBuilder.Entity<Foo>()
        .HasMany(p => p.RelatedFoo)
        .WithMany()
        .Map(m =>
        {
            m.MapLeftKey("FooId");
            m.MapRightKey("RelatedFooId");
            m.ToTable("RelatedFoos");                
        });

This result in a migration is like this

CreateTable(
            "dbo.RelatedFoos",
            c => new
                {
                    FooId= c.Int(nullable: false),
                    RelatedFooId= c.Int(nullable: false),
                })
            .PrimaryKey(t => new { t.FooId, t.RelatedFooId })
            .ForeignKey("dbo.Foo", t => t.FooId)
            .ForeignKey("dbo.Foo", t => t.RelatedFooId )
            .Index(t => t.FooId)
            .Index(t => t.RelatedFooId );

Everything works as expected, I can do something like:

//Create new list of relatedFoos        
List<Foo> relatedFoos = new List<Foo>();
//Add Foo entities to this list
relatedFoos.Add(fooEntity1);
relatedFoos.Add(fooEntity2);
//Add this List to a main Foo entity
Foo mainFooEntity.RelatedFoo = relatedFoos;
//Save this
db.Entry(mainFooEntity).State = EntityState.Modified;
db.SaveChanges();

And the relatedFoos are saved in the new table (RelatedFoos)

The problem comes when I try to delete this relatedFoos... I've already tried:

//Starting from a main Foo Entity
mainFooEntity.RelatedFoo = null;
db.Entry(mainFooEntity).State = EntityState.Modified;
db.SaveChanges();

This does not delete the data of "RelatedFoos" neither does assigning mainFooEntity.RelatedFoo to an empty List<Foo> or either deleting the current data. How can I delete this List<>?


Solution

  • I can't find a solution to this, so I end creating by myself a new Entitie "RelatedFoos" but whitout modelBuilder, this new entitie it's only a relationship table for create "Foo" against "Foo" N relations.

    I create the Model and add to DbContext, create migration, so, in this way I can use this Model Class for make updates or deletes without problem.

    Thanks in advance.