我对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; }
}
对于我的控制器,我设置他关注删除帖子:
[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");
}
问题是无论如何都无法发挥作用; I read this post但我似乎只适用于关系是一对一的模型,所以我迷失在这里,我到处搜索,无法找到解决这个问题的方法,如果有的话可以指出我错过了什么会非常好:),提前感谢,再次,原谅我的诺言,我刚开始,但想要解决一个大项目,以便能够学习一个很多。
答案 0 :(得分:16)
这是因为默认情况下EF不会强制执行可选关系的级联删除。模型中的关系被推断为可选。
您可以添加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; }
}
或者使用流畅的API配置它
modelBuilder.Entity<BlogEntry>()
.HasRequired(b => b.ParentBlog)
.WithMany(b => b.BlogEntries)
.WillCascadeOnDelete(true);
答案 1 :(得分:1)
不确定你在这里要做什么,但是你有一条记录,所以不确定你为什么要尝试循环。这是我的删除代码:
public ActionResult Delete(int id)
{
try {
Products products = context.Products.Single(x => x.productId == id);
return View(products);
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
CompileAndSendError(ex);
return View(new Products());
}
}
//
// POST: /Products/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
try {
Products products = context.Products.Single(x => x.productId == id);
context.Products.Remove(products);
context.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception ex)
{
ModelState.AddModelError("",ex.Message);
CompileAndSendError(ex);
return RedirectToAction("Index");
}
}