EF: many to many cascades

I have two objects that must have many different relationships. I am providing test data.

public class A
{
    public int AId {get;set;}
    public virtual ICollection<B> Bs {get;set;}
}

public class B
{
    public int BId {get;set;}
    public virtual ICollection<A> As {get;set;}
}

public class AMap : EntityTypeConfiguration<A>
{
    public AMap()
    {
        HasMany(e => e.Bs)
            .WithMany(e => e.As)                
            .Map(x =>
            {
                x.ToTable("AandB");
                x.MapLeftKey("AId");
                x.MapRightKey("BId");
            });
    }

}

      

In this configuration, I need to install cascading delete. For example, when I delete any row in table A, I need all related rows in table AandB to be deleted. But I cannot find the syntax for many for many. Help me?

+3


source to share


2 answers


After searching, I found a solution. To remove an object from a many-to-many relationship, you need to load the appropriate navigation property In my case:



var AtoDelete= context.As.Include(a => a.Bs) .First(); //include is mandatory
context.As.Remove(AtoDelete);
context.SaveChanges();//deletes will be issued to AandB table also.

      

+3


source


As I know there is no way to directly enable cascading deletes in many associations in the fluent API. you must explicitly delete related objects.



var a = context.A.Include(a => a.Bs).First();
foreach(var b in a.Bs)
{
    context.Entry(b).State = EntityState.Deleted;
}
context.Entry(a).State = EntityState.Deleted;
context.SaveChanges();

      

0


source







All Articles