【发布时间】:2018-12-29 18:26:51
【问题描述】:
我真的想不通。我经常遇到这个错误,我不确定如何修改代码以支持一对多。到目前为止我读过的例子很难理解。有人建议修改 Fluent API 或模型甚至控制器。
错误:
SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“CompetitionCategory”中插入标识列的显式值。
System.Data.SqlClient.SqlCommand+c.b__122_0(任务结果)DbUpdateException:更新条目时出错。有关详细信息,请参阅内部异常。
Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancelToken)
Competition模型类:
public class Competition
{
[Key]
public int ID { get; set; }
[Required]
[Display(Name = "Competition Name")]
public string CompetitionName { get; set; }
[Required]
public string Status { get; set; }
public ICollection<CompetitionCategory> CompetitionCategories { get; set; }
}
CompetitionCategory模型类:
public class CompetitionCategory
{
[Key]
public int ID { get; set; }
[Required]
[Display(Name = "Category Name")]
public string CategoryName { get; set; }
[ForeignKey("CompetitionID")]
public int CompetitionID { get; set; }
}
经过一番修改,我意识到要将列表传递给控制器,我应该使用如下所示的视图模型:
public class CategoriesViewModelIEnumerable
{
public Competition competition { get; set; }
public CompetitionCategory competitionCategory { get; set; }
// From Microsoft
public IEnumerable<string> SelectedCategories { get; set; }
public List<SelectListItem> CategoriesList { get; } = new List<SelectListItem>
{
new SelectListItem { Value = "xxx", Text = "xxx" },
new SelectListItem { Value = "yyy", Text = "yyy" },
new SelectListItem { Value = "zzz", Text = "zzz" },
};
}
我可以成功地将数据传递给我的控制器并在控制台上读取/打印它。但是我遇到了最后一个错误,即将第二个类别向前保存到数据库中,可能是由于一些主键/外键限制。
我目前只能将列表中的第一项保存到数据库中。
public async Task<IActionResult> Create(CategoriesViewModelIEnumerable model)
{
if (ModelState.IsValid)
{
CompetitionCategory competitionCategory = new CompetitionCategory();
_context.Add(model.competition);
await _context.SaveChangesAsync();
foreach (var CategoryName in model.SelectedCategories)
{
competitionCategory.CategoryName = CategoryName;
competitionCategory.CompetitionID = model.competition.ID;
_context.Add(competitionCategory);
await _context.SaveChangesAsync();
}
await _context.SaveChangesAsync();
}
}
非常感谢您的帮助! :)
【问题讨论】:
标签: c# asp.net-core asp.net-core-mvc ef-core-2.0 ef-core-2.1