I think you need to set up a one-to-one relationship using the Fluent API:
public class MyContext : DbContext {
And entity classes:
public class User { [Key] public int user_id {get;set;} public string username {get;set;} public string email {get;set;} public virtual User_Profile user_profile {get;set;} } public class User_Profile { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int user_id {get;set;} public string firstname {get;set;} public string lastname {get;set;} }
You must disconnect DatabaseGeneratedOption from Identity to None in one of the classes. I changed the primary and the dependent, as it seems that User should be primary. [ForeignKey(...)] not required because EF recognizes user_id in User_Profile as the FK property for User .
Code like this ...
using (var context = new MyContext()) { var user = new User(); var userProfile = new User_Profile(); user.user_profile = userProfile; context.Users.Add(user); context.SaveChanges(); }
... should work when you expect, and save both related objects in the database.
source share