I really cannot figure this out. I am constantly hitting this error and I am unsure how to modify the code to support 1 to many. The examples I have read up so far are quite difficult to understand. Some suggest modifying fluent API or the model or even the controller.
Error:
SqlException: Cannot insert explicit value for identity column in table 'CompetitionCategory' when IDENTITY_INSERT is set to OFF.
System.Data.SqlClient.SqlCommand+<>c.b__122_0(Task result)DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
Competition model class:
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 model class:
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; }
}
After some tinkering, I realised to pass the list to the controller I should use a view model as shown here:
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" },
};
}
I can successfully pass the data to my controller and read/print it on the console. However I am hitting the last error which is to save the 2nd category onwards into the database, probably due to some primary key/foreign key restriction.
I can currently only save the first item in the list into the database.
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();
}
}
Appreciate your help a lot! :)