EF:多对多级联删除

时间:2014-10-08 07:44:03

标签: c# .net entity-framework many-to-many entity-framework-6

我有两个应该有多对多关系的实体。我提供测试数据。

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");
            });
    }

}

在这个配置中,我需要设置级联删除。例如,当我删除表A中的任何行时,我需要删除表AandB中的所有相关行。但是我找不到多对多的语法。可以任何人帮我?

2 个答案:

答案 0 :(得分:3)

搜索后我找到了解决方案。要从多对多关系中删除实体,您需要加载相关的导航属性 就我而言:

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.

答案 1 :(得分:0)

据我所知,没有办法在流畅的API中直接打开多对多关联的级联删除。你必须明确删除相关实体。

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