简体   繁体   English

实体框架-删除级联

[英]Entity framework - Delete cascade

when I create my DbContext, I want all tables in my database to have delete-cascade enabled. 创建DbContext时,我希望数据库中的所有表都启用delete-cascade。 Is it possible? 可能吗?

I have two tables with FK. 我和FK有两张桌子。 The classes are 这些课程是

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

Now when I add 现在,当我添加

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

    }

The WithRequired clause does not have Child. WithRequired子句没有子级。 How do I solve that? 我该如何解决?

Cascade delete could be setup using FluentAPI in OnModelCreating method: 可以使用OnModelCreating方法中的FluentAPI设置级联删除:

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

UPD: Lets assume you have two entities Root and Node, which are connected with one-to-many relationship using DataAnnotations attributes: UPD:假设您有两个实体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; }
}

Now if you want to delete all Nodes while deleting the Root they're depend on, you need to configure this using FluenAPI in OnModelCreating method of your context configuration class using the code I introduced above before the UPD. 现在,如果要在删除所有节点时删除它们所依赖的根,则需要使用上下文配置类的OnModelCreating方法中的FluenAPI使用UPD之前在上面介绍的代码来配置此节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM