Clayton
Clayton

Reputation: 39

INSERT statement conflicted with the FOREIGN KEY

I have started this "support ticket" project where users can create tickets and the admin and user can both respond. I'm faily new to MVC3. I solve most issues on my own, but I have spent about 5 hours on this one searching Google/Stackoverflow and I just can't figure it out... so I've come to the experts.

This is the error:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Reponses_Tickets1". The conflict occurred in database "C:\USERS\ME\DOCUMENTS\VISUAL STUDIO 2010\PROJECTS\TICKETSYSTEM\TICKETSYSTEM\APP_DATA\TICKETSYSTEM.MDF", table "dbo.Tickets", column 'ID'.

Source Error:

Line 21:             response.Body = body;
Line 22:             model.AddToReponses(response);
Line 23:             model.SaveChanges();
Line 24:             return RedirectToAction("Ticket", new { id = id });
Line 25:            }

Here is the full controller action:

        public ActionResult Responses(int id, string body)
        {
            Ticket ticket = GetTicket(id);
            Response response = new Response();
            response.Body = body;
            model.AddToReponses(response);
            model.SaveChanges();
            return RedirectToAction("Ticket", new { id = id });
        }

For those wondering, I’ve been following the tutorial “From Zero to Blog in 100 Minutes” by matthewblagden (YouTube) but using it as a ticket system instead of a blog. I’ve following him line by line as I can tell.

Any help would be appreciated. Thanks.

Upvotes: 2

Views: 1085

Answers (1)

marc_s
marc_s

Reputation: 754268

Assuming every one of your responses is associated with a ticket somehow, you need to do this in your code, too!

public ActionResult Responses(int id, string body)
{
    // get the ticket
    Ticket ticket = GetTicket(id);

    // create resposne
    Response response = new Response();
    response.Body = body;

    // *** BEGIN NEW SECTION ***
    // here, you need to ASSOCIATE your response to the ticket you're retrieved!
    response.Ticket = ticket;  // or something like that......

    // or maybe:
    response.TicketId = ticket.Id;  // or something like that......
    // *** END NEW SECTION ***

    model.AddToReponses(response);
    model.SaveChanges();

    return RedirectToAction("Ticket", new { id = id });
}

Right now, you have stand-alone responses (not associated with any Ticket) - and that obviously doesn't work in your database.

Upvotes: 3

Related Questions