首页 > 解决方案 > 如何删除“A”实体中的项目并删除“B”实体中由 FK 链接到“A”实体的所有其他项目

问题描述

我正在使用 ASP.NET MVC 为论坛构建应用程序。我有一个名为“Posts”的实体和一个名为“PostReplies”的实体。

在特定的帖子上,会有一个回复列表,这些回复列表由我的“PostReplies”实体中的 FK:“Post_Id”链接。

我想知道我将如何删除一个帖子,然后删除链接到该帖子的回复。

我已使用 Fluent API 尝试解决此问题,但收到以下错误消息:

在模型生成期间检测到一个或多个验证错误:

“BookClub.Data.IdentityUserLogin: : EntityType 'IdentityUserLogin' 没有定义 > 键。定义此 EntityType 的键。BookClub.Data.IdentityUserRole: : EntityType 'IdentityUserRole' 没有定义?> 键。定义此 EntityType 的键。 “

我正在使用 MVC 的默认 ApplicationDbContext,因此在我的数据库中有 ApplicationUser 的表。

有谁知道如何纠正这个问题?

后实体模型

public class Post
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public DateTime Created { get; set; }

    public virtual Discussion Discussion { get; set; }
    public virtual ICollection<PostReply> Replies { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
}

回复后实体模型

public class PostReply
{
    public int Id { get; set; }
    public string Content { get; set; }
    public DateTime Created { get; set; }

    public virtual Post Post { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
}

删除方法/逻辑

    public void DeletePost(Post post)
    { 

       var deletePost = _context.Post.FirstOrDefault(p => p.Id == id);

        if (deletePost != null)
        {

            _context.Post.Remove(deletePost);
            _context.SaveChanges();
        }

    }

后控制器

   [HttpGet]
    public ActionResult DeletePost(int id)
    {

        return View(_postService.GetPost(id));
    }

    [HttpPost]
    public ActionResult DeletePost(Post post)
    {
         var posts = new Post();

            _postService.DeletePost(id, post);


       return RedirectToAction("GetPostsByDiscussion","Discussion", 
         new { id = post.Id })

    }

我使用了 Fluent API 并编写了以下代码:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<PostReply>()
            .HasRequired(p => p.Post)
            .WithMany(p => p.Replies)
            .HasForeignKey(r => r.PostId)
            .WillCascadeOnDelete(false);

    }

标签: asp.netasp.net-mvcmodel-view-controller

解决方案


您需要在您的实体之间添加关系DBContext

这可能是一对多、一对一、多对多

你可以在这里找到详细的文档

编辑:

我正在使用 MVC 的默认 ApplicationDbContext,因此在我的数据库中有 ApplicationUser 的表。

如果你继承ApplicationDbContext你应该在你的模型创建方法中调用该base.OnModelCreating()方法。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<PostReply>()
        .HasRequired(p => p.Post)
        .WithMany(p => p.Replies)
        .HasForeignKey(r => r.PostId)
        .WillCascadeOnDelete(true);
}

要启用级联删除,您应该发送真正的参数,例如.WillCascadeOnDelete(true)


推荐阅读