MVC .Net Cascade Deleting when using EF Code First Approach

后端 未结 2 1317
情歌与酒
情歌与酒 2021-02-14 06:10

I\'m pretty new to MVC and i\'m having troubles with cascade deleting. For my model I the following 2 classes:

    public class Blog
    {
        [Key]
                 


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-14 06:19

    That is because EF by default does not enforce cascade deletes for optional relationships. The relationship in your model is inferred as optional.

    You can add a non nullable scalar property(BlogId) of the 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 Comments { get; set; }
        public List Tags { get; set; }
        public DateTime CreationDateTime { get; set; }
        public DateTime UpdateDateTime { get; set; }
    
        public int ParentBlogId { get; set; }
    
        public virtual Blog ParentBlog { get; set; }
    }
    

    Or configure this using fluent API

       modelBuilder.Entity()
                .HasRequired(b => b.ParentBlog)
                .WithMany(b => b.BlogEntries)
                .WillCascadeOnDelete(true);
    

提交回复
热议问题