I am trying to save cascading in EF 4.1 code first.
[Table("User")]
public class User
{
[Key]
public Int64 UserId { get; set; }
public virtual UserRole UserRole { get; set; }
}
[Table("UserRole")]
public class UserRole
{
[Key,Column(Order = 0)]
public int RoleID { get; set; }
[Key,Column(Order = 1)]
public Int64 UserId { get; set; }
}
when I am trying to save the user by populating the userrole inside it. it is giving error.
The INSERT statement conflicted with the FOREIGN KEY constraint
“FK_User_UserRole”. The conflict occurred in database “x”, table
“dbo.User”, column ‘UserId’. The statement has been terminated.
using (Database database = new Database())
{
database.User.Add(user);
database.SaveChanges(); //it is giving error here.
}
Any ideas?
You need to configure the shared primary key mapping. Otherwise EF can not order the insert statements properly. In your case a
Userrecord has to be inserted first and then insert theUserRolewith the generated primary key ofUser.In your
OnModelCreatingmethodThen