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?