Hi guys, I´m new to ASP.NET Core and EF 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 MonthId 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_MonthId;. The conflict occurred in database Portal_RNT, table dbo.Months , column MonthId;.
The statement has been terminated.
Here is the code:
HTML
Goals Model
Month Model
Goals Controller
Best Regards
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 MonthId 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_MonthId;. The conflict occurred in database Portal_RNT, table dbo.Months , column MonthId;.
The statement has been terminated.
Here is the code:
HTML
@model ProjectName.Models.Goals
<div><formasp-controller="Goals"asp-action="Create">
Other form elements
<selectname="months"asp-for="MonthId"class="form-control"asp-items="ViewBag.Months">
</select>
<inputtype="submit"value="Save"class="btn btn-primary"/></form></div>
Goals Model
publicclass Goals
{
[Display(Name = "Code")]
publicInt32 GoalId { get; set; }
publicString GoalName{ get; set; }
public Months Month{ get; set; }
publicInt32 MonthId{ get; set; }
....
Other properties
}
Month Model
publicclass Months
{
[Key]
[Display(Name = "Code")]
publicInt32 MonthId { get; set; }
[Display(Name = "Designation")]
publicString 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