Hi guys, I´m new to ASP.NET Core and I have the following problem:
I have two related objects, Goals and Months, Goals got the foreign key of Months, and when I try to save the data of goals I got a foreign key error because the value of Months is 0, but when I create the select in the HTML I got correct code value.
Description of the error:
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Goals_Months_MonthId". The conflict occurred in database "Database Name", table "dbo.Months", column 'MonthId'.
The statement has been terminated.
Here´s the code:
HTML
@model ProjectName.Models.Goals
<div><form asp-controller="Goals" asp-action="Create"> Other form elements<select name="months" asp-for="MonthId" class="form-control" asp-items="ViewBag.Months"></select><input type="submit" value="Save" class="btn btn-primary" /></form></div>
Goals Model
public class Goals { [Display(Name = "Code")] public Int32 GoalId { get; set; } public String GoalName{ get; set; } public Months Month{ get; set; } public Int32 MonthId{ get; set; } .... Other properties }
Month Model
public class Months { [Key] [Display(Name = "Code")] public Int32 MonthId { get; set; } [Display(Name = "Designation")] public String Designation{ get; set; } }
Goals Controller
public IActionResult Create(Goals goal) { if (ModelState.IsValid) { _context.Goals.Add(goal); _context.SaveChanges(); } return View("~/../Create.cshtml");
}
Best Regards