none
SaveChanges RRS feed

  • Question

  • Hallo!

    In my controller, I have an Details method to display the view, and an Details POST method to save the changes:

     public ActionResult Details()
            {
                return View();
            }
            [HttpPost]
            public ActionResult Details(CandidatesSkills candidateSkills)
            {
                data.CandidatesSkills.AddObject(candidateSkills);
                data.SaveChanges();
                return RedirectToAction("Create","Home");
            }
    
    But I'm getting an error saying:

    The INSERT statement conflicted with the FOREIGN KEY constraint "FK_CandidatesSkills_Candidate". The conflict occurred in database "Candidates", table "dbo.Candidate", column 'CandidateID'.
    The statement has been terminated.

    Please help.

    Saturday, July 30, 2011 9:29 AM

All replies

  • Hello,

    I when you are inserting data in database that time your foreign key field goes as null or that value is not present in your primary key table so check this.

    Saturday, July 30, 2011 10:00 AM
  • This is my table definition:

    CREATE TABLE Candidate
    (
    CandidateID    int    IDENTITY(1,1) PRIMARY KEY,
    FirstName    nvarchar(50) NOT NULL,   
    LastName    nvarchar(50) NOT NULL,
    Email    nvarchar(50)  NOT NULL
    )


    create table CandidatesSkills
    (
    CandidateID int,
    SkillID int,
    SkillLevel nvarchar(50) not null,
    primary key(CandidateID,SkillID)
    )

    CREATE TABLE Skill
    (
    SkillID    int    IDENTITY(1,1) PRIMARY KEY,
    SkillName    nvarchar(50) NOT NULL,   
    )   

    Saturday, July 30, 2011 11:07 AM
  • Was you CandidatesSkill was mapped correctly to a Skill and a Candidate?

    You should first link your candidateSkill like so:

    CandidatesSkills candidateSkills  = new CandidatesSkills ;

    candidateSkills.Skills.Add(mySkill);

    candidateSkills.Candidates.Add(myCandidate);

    data.SaveChanges();

     

    Note that the candidateSkills  will be automaticlly added to the candidateSkill table since it's was linked to an Context's object.

     

    i hope it solves your problem.

    Monday, August 1, 2011 6:25 PM
  • Hello,

    Thank you for posting.

    Entity Framework needs to know about the FK constraint before it decide which table to insert into first. I suggest you can modify SSDL file to declare the FK constraint.

    Please feel free to let us know how it goes.

    Best Regards,


    Larcolais Gong[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, August 2, 2011 7:30 AM