MVC .Net Cascade在使用EF Code First Approach时删除
发布时间:2020-12-05 03:42:50 所属栏目:asp.Net 来源:互联网
导读:我对MVC很新,我有级联删除的麻烦.对于我的模型我以下2个类: public class Blog { [Key] public int Id { get; set; } [Required] public string Name { get; set; } [DisplayFormat()]
|
我对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; }
}
对于我的控制器,我设置他在删除帖子后继续: [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但是我似乎只适用于关系是一对一的模型,所以我在这里失去了,我有无处不在的搜索,找不到这个问题的解决方案,如果有人可以指出我错过了什么这真的很好:),谢谢提前,再次,赦免我的nooobness我刚刚开始,但想要解决一个大项目,以能够学到很多. 解决方法这是因为默认情况下,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); (编辑:东莞站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – 使用Razor视图引擎 – 如何格式化十进制值以
- asp.net html控件的File控件实现多文件上传实例分享
- asp.net – 从DropdownList SelectedItem获取属性
- asp.net – Mocking HttpContext不起作用
- .net – DNU发布 – 来自MSBuild的no-source
- asp.net – 如何访问Global.asax静态成员?
- ASP.NET成员:拒绝用户阻止CSS,页面无法正确呈现?
- ASP.NET对大文件上传的解决方案
- asp.net-mvc-3 – ASP.Net MVC 3:在哪里处理会话丢失?
- asp.net – IIS Express(WebMatrix)打开外部连接
推荐文章
站长推荐
- ASP.Net WebAPI与Ajax进行跨域数据交互时Cookies
- ASP.NET MembershipProvider加密/解密
- asp.net+js 实现无刷新上传解析csv文件的代码
- asp.net – Windows应用程序与Web应用程序开发
- asp.net – Azure可以运行WPF吗?
- asp.net – UserControl Viewstate在回发后丢失所
- asp.net-mvc – 带vNext的MVC 6:我们还需要Glob
- asp.net-mvc – ASP.net MVC DropDownList预选项
- Asp.NEt邮箱验证修改密码通过邮箱找回密码功能
- asp-classic – 从Classic ASP执行存储过程
热点阅读
