Reputation: 1757
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?
Upvotes: 3
Views: 1988
Reputation: 1757
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();
}
}
Upvotes: 1