SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint

asp.net-mvc c# ef-code-first entity-framework-core

Question

Hello and thank you in advance for taking time to read this post. I am new to EF Core and I am attempting to setup the following database connection where I have scaffold-ed controllers from the models.

namespace VotingWebApp.Models
{
  public class QuestionObject
  {
    public int QuestionObjectID { get; set; }
    public string Question { get; set; }
    public string AnswerA { get; set; }
    public string AnswerB { get; set; }
    public int AnswerAVote { get; set; }
    public int AnswerBVote { get; set; }
    public int GroupItemID { get; set; }
    public ICollection<ResponseItem> ResponseItems { get; set; }
    public GroupItem GroupItem { get; set; }
  }
}


namespace VotingWebApp.Models
{
    public class GroupItem
    {
        public int GroupItemID { get; set; }
        public string GroupName { get; set; }
        public int MemberCount { get; set; }
        public int Host { get; set; }
        public ICollection<GroupUserLink> GroupUserLinks { get; set; }
        public ICollection<QuestionObject> QuestionItems { get; set; }
    }
}

I receive the following error when I attempt to create a new QuestionObject in the database (Even when I supply an existing GroupItem key).

SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_QuestionObject_GroupItem_GroupItemID". The conflict occurred in database "aspnet-VotingWebApp-02945df4-961a-4b8f-8999-19aa61dfd02e", table "dbo.GroupItem", column 'GroupItemID'.

I am not sure how to go about solving this conflict. I have read other posts and they mainly highlight how the person is not supplying an existing key. I am new to EF Core so any help would be appreciated.

    // GET: QuestionObjects/Create
    public async Task<IActionResult> CreateQuestion(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var groupItem = await _context.GroupItem.SingleOrDefaultAsync(m => m.GroupItemID == id);
        if (groupItem == null)
        {
            return NotFound();
        }
        QuestionObject questionObject = new QuestionObject();
        questionObject.GroupItemID = groupItem.GroupItemID;
        return View(questionObject);
    }

    // POST: QuestionObjects/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> CreateQuestion([Bind("AnswerA,AnswerAVote,AnswerB,AnswerBVote,GroupID,Question")] QuestionObject questionObject)
    {
        if (ModelState.IsValid)
        {
            _context.Add(questionObject);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        return View(questionObject);
    }

I have added the code for the insertion. This is within the GroupItem controller.

1
0
2/10/2017 5:42:37 PM

Accepted Answer

This looks more like a binding problem. First, your white list of included fields does not have GroupItemID so add it (unless GroupId was a typo):

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateQuestion([Bind(Include="AnswerA,AnswerAVote,AnswerB,AnswerBVote,GroupID,GroupItemID,Question")] QuestionObject questionObject)
{
    if (ModelState.IsValid)
    {
        _context.QuestionObjects.Add(questionObject);
        await _context.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    return View(questionObject);
}

Next, you need to either have an input field or hidden field on your view for GroupItemID or it will come back null

@Html.HiddenFor(m => m.GroupItemID)
1
2/10/2017 7:03:45 PM

Popular Answer

Try out populating GroupItem object on QuestionObject to help EF understand FK relationship.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateQuestion([Bind("AnswerA,AnswerAVote,AnswerB,AnswerBVote,GroupID,Question")] QuestionObject questionObject)
{
    if (ModelState.IsValid)
    {
        questionObject.GroupItem = _context.GroupItem.Single(m => m.GroupItemID == questionObject.GroupItemID)
        _context.Add(questionObject);
        await _context.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    return View(questionObject);
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow