I want to create a 1 to 1 relationship by code first, below is my code,
class Person
{
public int id { get; set; }
public string Name { get; set; }
public virtual PersonDetail detail { get; set; }
}
class PersonDetail
{
public int id { get; set; }
public double Height { get; set; }
public double Weight { get; set; }
public virtual Person person { get; set; }
}
class EFTest : DbContext
{
public DbSet<Person> personSet { get; set; }
public DbSet<PersonDetail> detailSet { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>().HasRequired(x => x.detail).WithRequiredPrincipal(x => x.person);
}
}
But I still can insert a person without person detail. I’m trying to create a 1 to 1 relationship in model first, it works well, if I insert one end without the other end, there will be an exception thrown. Why code first with the code above create a 1 to 0..1 relationship?
Anyone can help?
That is possible only if both
PersonandPersonDetailwill be mapped to the same table (the mapping technique is called Table Splitting) because strict 1:1 means that you cannot insertPersonwithout existingPersonDetailbut you also cannot insertPersonDetailwithout existingPerson=> you cannot insert either of them because the dependency will be always missing (remember each record has its own insert command and database check the integrity after each command not after transaction).Only when you use table splitting EF will create single insert command containing data from both entities. In your entity model it will look like two entities with 1:1 mapping but in database it will be single table.