我对 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; }
}
对于我的 Controller ,我将他设置为删除回帖:
[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但我似乎只适用于一对一关系的模型,所以我在这里迷路了,我到处搜索,但找不到这个问题的解决方案,如果有人能指出我遗漏了什么会非常好:),提前致谢,再次请原谅我的菜鸟,我才刚刚开始,但想要解决一个大项目,以便能够学到很多东西。
最佳答案
这是因为默认情况下 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; }
}
或者使用 fluent API 进行配置
modelBuilder.Entity<BlogEntry>()
.HasRequired(b => b.ParentBlog)
.WithMany(b => b.BlogEntries)
.WillCascadeOnDelete(true);
关于.net - 使用 EF Code First 方法时的 MVC .Net 级联删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9241704/