使用EntityFramework删除级联

时间:2015-06-12 20:37:47

标签: entity-framework

在模型中列出了类(简化):

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);
    }
}

问题: 当我试图删除子类别(具有NOT NULL Category_Id)=&gt;删除成功,但是当我需要删除根类别(Category_Id = NULL)时,有一个例外:DELETE语句与REFERENCE约束“FK_Topic_Category”冲突。 是的,我可以先删除根类别中的参考主题,然后删除类别。但是想知道为什么在root情况下级联删除不起作用。

1 个答案:

答案 0 :(得分:0)

好的,只需在数据库注释中将ON DELETE CASCADE添加到子实体的FK中。