EF:Many to many cascade delete

.net c# entity-framework entity-framework-6 many-to-many

Question

I have two entities that should have many to many relationship.I provide 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 set cascade delete.For example when I delete any row in table A,I need that all related rows in table AandB will be deleted.But I can't find syntax for many to many.Can anybody help me?

1
3
10/8/2014 8:04:24 AM

Accepted Answer

After searching I've found solution.To delete entity from many-to-many relationship you need load the related 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
10/8/2014 9:49:58 AM

Popular Answer

As I know there is no way to directly turn on cascade deletes on Many to Many associations in fluent API. you have to delete related entities explicitly.

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();


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow