gpt4 book ai didi

c# - EF :Many to many cascade delete

转载 作者:行者123 更新时间:2023-11-30 16:10:12 24 4
gpt4 key购买 nike

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

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 中的任何行时,我需要删除表 A 和 B 中的所有相关行。但是我找不到多对多的语法。任何人都可以帮我?

最佳答案

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

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.

关于c# - EF :Many to many cascade delete,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26251639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com