I have 2 Entities User and User_Profile (one to one relationship). I have linked them as follows:
public class User
{
[Key]
[ForeignKey("user_profile")]
public int user_id {get;set;}
public string username {get;set;}
public string email {get;set;}
public virtual User_Proile user_profile {get;set;}
}
public class User_Profile
{
[Key]
public int user_id {get;set;}
public string firstname {get;set;}
public string lastname {get;set;}
}
user_id is a PK in both SQL Server’s User and User_Profile tables. It is also set as an Identity column in the User table.
When I try to insert a new record via the EFDBContext Add/SaveChanges. I get the following error: “user_id cannot be NULL in the User_Profile table” This makes perfect sense as this is a PK column. I was hoping EF would be able to take the Identity user_id from Users and Insert it into User_Profile user_id when saving.
Is this possible and if so how would I implement that?
UPDATE: Please note that I manually created the DB tables and code classes so I dont have access to StoreGeneratedPattern via the .edmx file.
I think it is necessary to configure your one-to-one relationship explicitely using Fluent API:
And the entity classes:
It’s necessary to switch off
DatabaseGeneratedOptionfromIdentitytoNonein one of the classes. I have swapped principal and dependent as it seems that theUsershould be the principal. The[ForeignKey(...)]is not necessary because EF will recognizeuser_idinUser_Profileas a FK property toUser.A code like this…
…should work then as you expect and save both related entities to the database.