简体   繁体   English

EntityFramework 6:INSERT语句与FOREIGN KEY约束冲突,但父记录已保存

[英]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 . 我的数据库中有两个表UsersJobSeekerEmploymentDetails

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 ) 要在上面的表中插入记录,我的代码如下:(我正在使用EntityFramework 6AutoMapper

    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. 现在, User已保存到数据库中,我可以看到从保存的User对象中成功检索到ID的值。 But the last db.SaveChangesAsync() statement throws the following exception. 但是最后一个db.SaveChangesAsync()语句引发以下异常。

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); 这行Mapper.Map(employmentDetails, jobSeekerEmpDetail); would actually override the UserId to 0 which I set correctly in previous step. 实际上会覆盖我在上一步中正确设置的UserId到0。 I changed it the code to set the UserId after the mapping has been performed and it worked. 在执行映射并起作用之后,我将其代码更改为设置UserId

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 INSERT 语句与 FOREIGN KEY 约束冲突 语句已终止 - The INSERT statement conflicted with the FOREIGN KEY constraint The statement has been terminated 错误:INSERT语句与FOREIGN KEY约束冲突 - Error : INSERT statement conflicted with the FOREIGN KEY constraint INSERT语句与FOREIGN KEY约束错误冲突 - The INSERT statement conflicted with the FOREIGN KEY constraint error 错误-INSERT语句与FOREIGN KEY约束冲突 - Error - The INSERT statement conflicted with the FOREIGN KEY constraint {“INSERT语句与FOREIGN KEY约束冲突该语句已被终止。”} - {“The INSERT statement conflicted with the FOREIGN KEY constraint The statement has been terminated.”} 使用SimpleMembership的AddUserToRole时出错:INSERT语句与FOREIGN KEY约束冲突 - Error using AddUserToRole of SimpleMembership: INSERT statement conflicted with the FOREIGN KEY constraint BulkInsert:INSERT语句与FOREIGN KEY约束冲突 - BulkInsert: The INSERT statement conflicted with the FOREIGN KEY constraint “ INSERT语句与FOREIGN KEY约束冲突 - "The INSERT statement conflicted with the FOREIGN KEY constraint INSERT语句与FOREIGN KEY约束冲突 - The INSERT statement conflicted with the FOREIGN KEY constraint SqlException:INSERT语句与FOREIGN KEY约束冲突 - SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM