【发布时间】:2016-10-24 15:15:30
【问题描述】:
我有 3 个实体类,例如
public class Post {
[Key]
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public ICollection<PostTag> PostTags { get; set; }
}
public class Tag {
[Key]
public int TagId { get; set; }
public string TagName { get; set; }
public ICollection<PostTag> PostTags { get; set; }
}
public class PostTag {
public int PostId { get; set; }
public Post Post { get; set; }
public int TagId { get; set; }
public Tag Tag { get; set; }
}
这些类与实体框架 7 文档示例相同,我使用了同一示例中的 OnModelCreating 方法。
当我尝试编辑帖子时,我无法更新或修改 PostTags。
我在 PostsController 中的编辑方法是这样的
public async Task<IActionResult> Edit(int id, [Bind("PostId,Content,Title")] Post post)
{
if (id != post.PostId)
{
return NotFound();
}
if (ModelState.IsValid)
{
post.PostTags.Clear();
post.PostTags.Add(new PostTag
{
TagId = 2,
PostId = post.PostId
});
try
{
_context.Update(post);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PostExists(post.PostId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(post);
}
我尝试清除以前的帖子标签并添加新标签。但是新的 posttag 项目无法添加到数据库中。以前的 posttags 仍然存在于 DB 中。这意味着此方法对 posttags 属性不执行任何操作。在添加新帖子时它正在工作。 给我解决方案,在编辑帖子时添加或删除新的帖子标签以发布条目。
【问题讨论】:
-
我认为您还需要将 icollection 用于帖子和标签中的帖子标签,最好使用用户 lisnt 而不是 icollection 并且在您的数据库上下文中您需要在模型构建器中定义关系
标签: asp.net-core-mvc entity-framework-core