asp.net - 如何删除“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);
}
解决方案
您需要在您的实体之间添加关系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)
推荐阅读
- r - 有没有办法计算数据框列中的观察次数并将其保存为字符串?
- mongodb - 如何更快地执行此 mongoDB 查找聚合?
- c# - 如何防止标签在 for 循环中相互重叠
- javascript - 如何将一个列表中的值存储到特定属性的另一个列表中?
- scss-mixins - SCSS mixin 第二个参数未正确编译
- c - 在STM32上调用Timer_callback时丢失指针地址
- r - 如何在R中的几个步骤中收集列而不丢失分组
- c# - 如何在请求中传递字符串列表?
- django - 工作服:错误 - 在我的使用 Docker 容器的应用程序中没有来源
- gradle - 使用 farmRun 任务时不应用 Gretty 配置