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

时间:2011-09-26 13:16:44

标签: entity-framework entity-framework-4 entity-framework-4.1

我收到此错误:

  

System.Data.SqlClient.SqlException DELETE语句发生冲突   使用REFERENCE约束“FK_ comments _postId__164452B1”。该   数据库“awe”,表“dbo.comments”,列中发生冲突   “帖子ID”。声明已经终止。

我有这个结构:

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

我的删除方法:

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

我的DbContext:

public class Db : DbContext
{
    public DbSet<Post> Posts { get; set; }
    public DbSet<Comment> Comments { get; set; }
}

1 个答案:

答案 0 :(得分:25)

听起来你要删除的帖子有子评论。

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

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

相关问题