Dot-Net

使用 EF 程式碼優先方法時的 MVC .Net 級聯刪除

  • December 7, 2018

我對 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");
}

問題是無論如何它都行不通;我讀了這篇文章,但我似乎只適用於關係是一對一的模型,所以我在這裡迷路了,我到處搜尋,找不到這個問題的解決方案,如果有人能指出我’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’''

這是因為預設情況下 EF 不強制對可選關係進行級聯刪除。模型中的關係被推斷為可選。

BlogId您可以添加FK的不可為空的標量屬性 ( )

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);

引用自:https://stackoverflow.com/questions/9241704