EF - 级联删除不起作用,无法删除对象

Omu*_*Omu 6 entity-framework entity-framework-4 entity-framework-4.1

我收到此错误:

System.Data.SqlClient.SqlException DELETE语句与REFERENCE约束"FK_ comments _postId__164452B1" 冲突.冲突发生在数据库"awe",表"dbo.comments",列'postId'中.该语句已终止.

我有这个结构:

    public class Post
    {
        public long Id { get; set; }
        public string Body { get; set; }     

        public long? ParentId { get; set; }
        public virtual Post Parent { get; set; }
        public virtual ICollection<Post> Posts { get; set; }

        public virtual ICollection<Comment> Comments { get; set; }
    }

    public class Comment
    {
        public long Id { get; set; }
        public long PostId { get; set; }
        public virtual Post Post { get; set; }
        public string Body { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

我的删除方法:

    public void Delete(long id)
    {
        var p = context.Set<Post>().Get(id);
        if(p == null) throw new MyEx("this post doesn't exist");
        if (p.Posts.Count > 0) throw new MyEx("this post has children and it cannot be  deleted");
        context.Set<Post>().Remove(p);
        context.SaveChanges();
    }
Run Code Online (Sandbox Code Playgroud)

我的DbContext:

public class Db : DbContext
{
    public DbSet<Post> Posts { get; set; }
    public DbSet<Comment> Comments { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Ian*_*son 25

听起来像你试图删除的帖子有子评论.

实体框架不负责在数据库中级联删除 - 它希望您通过在RDBMS中的外键关系上设置级联删除来实现此目的.

话虽如此,如果删除Entity Framework中的父实体,它将尝试为已加载到当前DbContext中的任何子实体发出delete语句,但它不会初始化尚未加载的任何子实体.如果未指定级联删除(例如您所看到的级联删除),这可能会导致RDBMS抛出外键约束违例异常.有关cascade delete如何在"实体框架"中"工作"的更多详细信息,请参阅此博客文章.