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\"
You have to set the StoreGeneratedPattern attribute to Identity in your .edmx file to let the framework know the field is generated by the database. This link might help...
Autonumber with Entity Framework
I think it is necessary to configure your one-to-one relationship explicitely using Fluent API:
public class MyContext : DbContext
{
// ... your DbSets
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasRequired(u => u.user_profile)
.WithRequiredPrincipal();
}
}
And the 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;}
}
It's necessary to switch off DatabaseGeneratedOption
from Identity
to None
in one of the classes. I have swapped principal and dependent as it seems that the User
should be the principal. The [ForeignKey(...)]
is not necessary because EF will recognize user_id
in User_Profile
as a FK property to User
.
A 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 then as you expect and save both related entities to the database.