EF:许多到许多级联删除
作者:互联网
我有两个应该有许多关系的实体.我提供测试数据.
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中的所有相关行.但是我找不到很多对很多的语法.有人可以帮我吗?
解决方法:
搜索后,我找到了解决方案.要从多对多关系中删除实体,您需要加载相关的导航属性
就我而言:
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.
标签:entity-framework-6,many-to-many,c,net,entity-framework 来源: https://codeday.me/bug/20191121/2049840.html