是否可以有选择地删除 Entity Framework 5 Code First 中自动生成的多对多链接表上的级联删除选项?这是一个需要它的简单示例:
public class Parent
{
public int Id { get; set; }
public virtual IList<ChildA> As { get; set; }
public virtual IList<ChildB> Bs { get; set; }
}
public class ChildA
{
public int Id { get; set; }
[Required]
public virtual Parent Parent { get; set; }
public virtual IList<ChildB> ChildBJoins { get; set; }
}
public class ChildB
{
public int Id { get; set; }
[Required]
public virtual Parent Parent { get; set; }
public virtual IList<ChildA> ChildAJoins { get; set; }
}
public class TestContext : DbContext
{
public DbSet<Parent> Parents { get; set; }
public DbSet<ChildA> As { get; set; }
public DbSet<ChildB> Bs { get; set; }
}
由于链接表上引入了级联删除选项,当前形式的上下文将不适用于数据库。如果我要创建手动链接表,我可以使用 Fluent API 将其一侧配置为不级联,但该选项在多对多关系中不可用。
我知道我可以通过删除ManyToManyCascadeDeleteConvention
as per 这个问题 https://stackoverflow.com/questions/13705441/how-to-disable-cascade-delete-for-link-tables-in-ef-code-first,但这不是我所追求的——我只想能够为一种关系做到这一点,或者最好是为一种关系的一侧做到这一点。
我怀疑在 EntityTypeConfiguration 映射类中无法做到这一点,但我通过更改 DbMigration 类中的 Up() 方法中的代码来做到这一点。
为链接表生成的代码是:
CreateTable(
"dbo.ChildBChildAs",
c => new
{
ChildB_Id = c.Int(nullable: false),
ChildA_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.ChildB_Id, t.ChildA_Id })
.ForeignKey("dbo.ChildBs", t => t.ChildB_Id, cascadeDelete: true)
.ForeignKey("dbo.ChildAs", t => t.ChildA_Id, cascadeDelete: true)
.Index(t => t.ChildB_Id)
.Index(t => t.ChildA_Id);
您应该能够通过将您不想级联的一侧更改为 false 来使其工作:
.ForeignKey("dbo.ChildAs", t => t.ChildA_Id, cascadeDelete: false)
如果你能像一对多一样使用 FluentAPI 来做到这一点,那就太好了,但我还没有找到一种方法来做到这一点
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)