Entity framework 使用EntityFramework进行级联删除

Entity framework 使用EntityFramework进行级联删除,entity-framework,Entity Framework,已在modelsimplified中列出了类: public partial class Category { public Category() { Topics = new HashSet<Topic>(); } public Guid Id { get; set; } public Guid? Category_Id { get; set; }//id for Parent category public vi

已在modelsimplified中列出了类:

public partial class Category
{
    public Category()
    {
        Topics = new HashSet<Topic>();
    }

    public Guid Id { get; set; }
    public Guid? Category_Id { get; set; }//id for Parent category

    public virtual ICollection<Topic> Topics { get; set; }
}

public partial class Topic
{
    public Topic()
    {
        Posts = new HashSet<Post>();
    }

    public Guid Id { get; set; }
    public string Name { get; set; }
    public Guid Category_Id { get; set; }

    public virtual ICollection<Post> Posts { get; set; }
    public virtual Category Category { get; set; }
}
模型如下:

public partial class EntityModel : DbContext
{
    public EntityModel()
        : base("name=EntityModelContext")
    {
        Configuration.LazyLoadingEnabled = true;
        Configuration.AutoDetectChangesEnabled = true;
        Debug.WriteLine("Context Created");
    }

    public virtual DbSet<Category> Category { get; set; }
    public virtual DbSet<Post> Post { get; set; }
    public virtual DbSet<Topic> Topic { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Category>()
            .HasMany(e => e.Topics)
            .WithRequired(e => e.Category)
            .HasForeignKey(e => e.Category_Id)
            .WillCascadeOnDelete(true);

        modelBuilder.Entity<Topic>()
            .HasMany(e => e.Posts)
            .WithRequired(e => e.Topic)
            .HasForeignKey(e => e.Topic_Id)
            .WillCascadeOnDelete(true);
    }
}
所以问题是: 当我试图删除没有NULL category_Id=>delete successful的子类别时,但当我需要删除根categoryCategory_Id=NULL时,有一个例外:delete语句与引用约束“FK_Topic_category”冲突。
是的,我可以先删除根类别中的引用主题,然后再删除类别。但是想知道为什么在根案例中级联删除不起作用。

好的,只是在DB注释中将delete cascade添加到子实体的FK中。

Hi-Renat。您是如何将删除级联添加到FK的?我也有同样的问题,但我所看到的解决方案似乎都无法解决。我在SQLite上使用EFCore2.0。