MVC .Net Cascade Deleting when using EF Code First Approach

时光怂恿深爱的人放手 提交于 2019-12-03 12:40:13

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

Or configure this using fluent API

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

Not sure what you are trying to do here, but you have one record so not sure why you are trying to loop. Here is my delete code:

public ActionResult Delete(int id)
{
    try {
        Products products = context.Products.Single(x => x.productId == id);
        return View(products);
    }
    catch (Exception ex)
    {
        ModelState.AddModelError("", ex.Message);
        CompileAndSendError(ex);
        return View(new Products());
    }
}

//
// POST: /Products/Delete/5

[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
    try {
        Products products = context.Products.Single(x => x.productId == id);
        context.Products.Remove(products);
        context.SaveChanges();
        return RedirectToAction("Index");
    }
    catch (Exception ex)
    {
        ModelState.AddModelError("",ex.Message);
        CompileAndSendError(ex);
        return RedirectToAction("Index");
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!