实体框架-删除级联

本文关键字:级联 删除 框架 实体 | 更新日期: 2023-09-27 18:08:30

当我创建DbContext时,我希望数据库中的所有表都启用了delete-cascade。这可能吗?

我有两张FK的表。类是

public class Child
{
    public int ChildID { get; set; }
    public string Name { get; set; }
    public virtual Parent parent { get; set; }
}
public class Parent
{
    public int ParentID { get; set; }
    public string Name {get;set;}        
}       
public class iMyContext : DbContext
{
    public iMyContext(string connectionString)
        : base(connectionString)
        {
        }

    public virtual DbSet<Child> Children { get; set; }
    public virtual DbSet<Parent> Parents { get; set; }  
}
On creating my context, I get tables as
Parents with columns
ParentID PK
Name
Children with columns
ChildID PK
Name
Parent FK

现在当我添加

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Child>()
        .HasOptional(r => r.Parent)
        .WithRequired(ad => ad.)   // problem here
        .WillCascadeOnDelete();
    }

WithRequired子句没有Child。怎么解呢?

实体框架-删除级联

级联删除可以使用OnModelCreating方法中的FluentAPI设置:

modelBuilder.Entity<Root>()
            .HasMany(r => r.Nodes)
            .WithRequired(n => n.Root)
            .WillCascadeOnDelete();

乌利希期刊指南:假设您有两个实体Root和Node,它们使用DataAnnotations属性以一对多关系连接:

public class Root
{
    [Key]
    public int RootId { get; set; }
    public string RootName { get; set; }
    [InverseProperty("Root")]
    public ICollection<Node> Nodes { get; set; }
}
public class Node
{
    [Key]
    public int NodeId { get; set; }
    public string NodeName { get; set; }
    [ForeignKey("Root")]
    public int RootId { get; set; }
    public Root Root { get; set; }
}

现在,如果你想删除所有节点,同时删除它们所依赖的根,你需要使用上下文配置类的OnModelCreating方法中的FluenAPI配置它,使用我在UPD之前介绍的代码。