.net - 使用 EF Code First 方法时的 MVC .Net 级联删除

标签 .net asp.net-mvc entity-framework-4.1 ef-code-first

我对 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/

相关文章:

.net - 如何测量源代码统计信息?

C#-根据与另一个列表的部分交集从列表中选择特定项目 (Linq + Lambda)

sql-server - “不存在数据时读取尝试无效” - Entity Framework 中发生异常 "sometimes"

entity-framework-4.1 - 无法隐式转换类型 'System.Collections.Generic.IEnumerable<System.Collections.Generic.ICollection

.net - 具有强类型且无大小限制的轻型 SQL 数据库

html - 在 MVC 中从 html 表单获取上传的文件?

c# - .NET Core 替代 ConvertTimeToUtc?

asp.net-mvc - Blazor WASM 页面路由

c# - 如何观察DbSet<T>的Add Action ?

.net - FileStream和StreamWriter-写入后如何截断文件的其余部分?