【发布时间】:2021-10-02 06:43:44
【问题描述】:
我想知道在提交表单时更新多对多关系的好习惯。
我得到了这两个实体,并使用 EF 核心 5 中的默认多对多关系:
public class BlogEntry
{
public int Id { get; set; }
[Required]
[MaxLength(200)]
public string Title { get; set; }
[Required]
public string EntryText { get; set; }
[NotMapped]
public IEnumerable<string> CategoriesToPublish { get; set; }
public ICollection<Category> Categories { get; set; }
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<BlogEntry> BlogEntries { get; set; }
}
上下文:
public DbSet<BlogEntry> BlogEntries { get; set; }
public DbSet<Category> Categories { get; set; }
我有一个带有多选字段的表单来表示这种关系。看图片 form
我没有在表单上使用关系属性(maube 我应该,但我不知道),我有另一个属性可以将关系转换为名为@987654325@ 的字符串列表,因此我可以加载多选并在帖子中检索选择。
在 post 操作方法上,我想迭代 this CategoriesToPublish 并更新所有关系。
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Publish(BlogEntry blogEntry)
{
if (ModelState.IsValid)
{
blogEntry.Categories = await _context.Categories.Where(x => x.BlogEntries.Any(x => x.Id == blogEntry.Id)).ToListAsync();
await UpdateCategories(blogEntry);
_context.Update(blogEntry);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(List));
}
return View(blogEntry);
}
但我面临的问题是Categories 关系未在回发时加载。如果我尝试手动加载它并保存上下文,我会收到一条错误消息SqlException: Violation of PRIMARY KEY constraint 'PK_BlogEntryCategory'. Cannot insert duplicate key in object 'dbo.BlogEntryCategory'
我不确定如何解决这个问题。有什么建议吗?
【问题讨论】:
标签: asp.net-core razor entity-framework-core entity-framework-core-5 entity-framework-core-5.0