我对MVC很新,我有级联删除的麻烦.对于我的模型我以下2个类:
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; } }@H_502_4@对于我的控制器,我设置他在删除帖子后继续:
[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"); }@H_502_4@问题是无论如何都不会工作I read this post但是我似乎只适用于关系是一对一的模型,所以我在这里失去了,我有无处不在的搜索,找不到这个问题的解决方案,如果有人可以指出我错过了什么这真的很好:),谢谢提前,再次,赦免我的nooobness我刚刚开始,但想要解决一个大项目,以能够学到很多.
解决方法
这是因为默认情况下,EF不会为可选关系强制执行级联删除.您的模型中的关系被推断为可选的.
@H_502_4@您可以添加FK的不可空标量属性(BlogId)
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; } }@H_502_4@或使用流畅的API进行配置
modelBuilder.Entity<BlogEntry>() .Hasrequired(b => b.ParentBlog) .WithMany(b => b.BlogEntries) .WillCascadeOnDelete(true);