使用EF Code First方法时MVC .Net Cascade删除

Q_r*_*_ro 11 .net asp.net-mvc ef-code-first entity-framework-4.1

我是MVC的新手,我在级联删除方面遇到了麻烦.对于我的模型,我有以下两个类:

    public class Blog
    {
        [Key]
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        [DisplayFormat()]
        public virtual ICollection<BlogEntry> BlogEntries { get; set; }
        public DateTime CreationDateTime { get; set; }
        public string UserName { get; set; }
    }

    public class BlogEntry
    {
        [Key]
        public int Id { get; set; }
        [Required]
        public string Title { get; set; }
        [Required]
        public string Summary { get; set; }
        [Required]
        public string Body { get; set; }
        public List<Comment> Comments { get; set; }
        public List<Tag> Tags { get; set; }
        public DateTime CreationDateTime { get; set; }
        public DateTime UpdateDateTime { get; set; }
        public virtual Blog ParentBlog { get; set; }

    }
Run Code Online (Sandbox Code Playgroud)

对于我的控制器,我设置他关注删除帖子:

[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
    Blag blog = db.Blogs.Find(id);

    foreach (var blogentry in blog.BlogEntries)
    {
        //blogentry = db.BlogEntries.Find(id);
        db.BlogEntries.Remove(blogentry);
    }
    db.Blogs.Remove(blog);
    db.SaveChanges();
    return RedirectToAction("Index");
}
Run Code Online (Sandbox Code Playgroud)

问题是无论如何都无法工作; 我读过这篇文章,但我似乎只适用于关系是一对一的模型,所以我迷失在这里,我到处都搜索,并且找不到解决这个问题的方法,如果有人能指出我是什么的我很想念它会很好:),提前谢谢,再次,原谅我的诺言,我刚刚开始,但想要解决一个大项目,能够学到很多东西.

Era*_*nga 16

这是因为默认情况下EF不会强制执行可选关系的级联删除.模型中的关系被推断为可选.

您可以添加BlogIdFK 的非可空标量属性()

public class BlogEntry
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Title { get; set; }
    [Required]
    public string Summary { get; set; }
    [Required]
    public string Body { get; set; }
    public List<Comment> Comments { get; set; }
    public List<Tag> Tags { get; set; }
    public DateTime CreationDateTime { get; set; }
    public DateTime UpdateDateTime { get; set; }

    public int ParentBlogId { get; set; }

    public virtual Blog ParentBlog { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

或者使用流畅的API配置它

   modelBuilder.Entity<BlogEntry>()
            .HasRequired(b => b.ParentBlog)
            .WithMany(b => b.BlogEntries)
            .WillCascadeOnDelete(true);
Run Code Online (Sandbox Code Playgroud)