简体   繁体   中英

EntityFramework 6: The INSERT statement conflicted with the FOREIGN KEY constraint Error but the parent record has been saved

I have two tables in my DB, Users and JobSeekerEmploymentDetails .

Users
---------------------------
ID        int (Auto Generated Primary Key)
Col1      ...

JobSeekerEmploymentDetails
---------------------------
ID        int (Auto Generated Primary Key)
Col1      ...
UserId    int (Foreign Key to Users table)

To insert the records in the above tables, my code is as follows: (I am using EntityFramework 6 and AutoMapper )

    public async Task<int> SaveJobSeeker(AccountInfoViewModel accountInfo, PersonalDetailViewModel personalDetail, EmploymentDetailsViewModel employmentDetails)
    {
        //create EF User object
        var user = new User {CreatedOn = DateTime.Now};

        //map data from the ViewModels into user class
        Mapper.Map(accountInfo, user);
        Mapper.Map(personalDetail, user);

        using (var db = new ITWebEntities())
        {
            //save user
            db.Users.Add(user);
            await db.SaveChangesAsync();

            //Create new EF class object and set recently saved user Id as foreign key value
            var jobSeekerEmpDetail = new JobSeekerEmploymentDetail { UserId = user.ID };

            //Map other detail from the ViewModel object           
            Mapper.Map(employmentDetails, jobSeekerEmpDetail);

            //save emp details info
            db.JobSeekerEmploymentDetails.Add(jobSeekerEmpDetail);
            return await db.SaveChangesAsync();
        }
    }

Now the User is saved into the DB and I can see that the value of ID is retrieved successfully from the saved User object. But the last db.SaveChangesAsync() statement throws the following exception.

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_EmploymentDetails_Users". The conflict occurred in database "ITWeb", table "dbo.Users", column 'ID'.
The statement has been terminated.

The constraint is set properly as you can see in the following screenshot:

在此处输入图片说明

I suppose I am doing something stupid but I am unable to figure it out. Can you help?

That was very simple. The line Mapper.Map(employmentDetails, jobSeekerEmpDetail); would actually override the UserId to 0 which I set correctly in previous step. I changed it the code to set the UserId after the mapping has been performed and it worked.

public async Task<int> SaveJobSeeker(AccountInfoViewModel accountInfo, PersonalDetailViewModel personalDetail, EmploymentDetailsViewModel employmentDetails)
{
    //create EF User object
    var user = new User {CreatedOn = DateTime.Now};

    //map data from the ViewModels into user class
    Mapper.Map(accountInfo, user);
    Mapper.Map(personalDetail, user);

    using (var db = new ITWebEntities())
    {
        //save user
        db.Users.Add(user);
        await db.SaveChangesAsync();

        //Create new EF class object and set recently saved user Id as foreign key value
        var jobSeekerEmpDetail = new JobSeekerEmploymentDetail();

        //Map other detail from the ViewModel object           
        Mapper.Map(employmentDetails, jobSeekerEmpDetail);

        jobSeekerEmpDetail.UserId = user.ID;

        //save emp details info
        db.JobSeekerEmploymentDetails.Add(jobSeekerEmpDetail);
        return await db.SaveChangesAsync();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM