0

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?

James
  • 2,570
  • 7
  • 34
  • 57
  • Is there a reason you want Person and PersonDetail seperate, instead of just putting them in the same entity? If one cannot live without the other, it doesn't seem like there's an advantage to model them seperate. I have done what you want before(not in EF, but using constraints in the DB) and it really just creates a headache. Anytime I try to insert either record, there is an error because it's partner does not exist. There is no way to insert two records simultaneously. Thus you would have to drop the constraints, insert both records, and then enable the constraints again. – AaronLS Jun 20 '12 at 15:12

1 Answers1

2

That is possible only if both Person and PersonDetail will be mapped to the same table (the mapping technique is called Table Splitting) because strict 1:1 means that you cannot insert Person without existing PersonDetail but you also cannot insert PersonDetail without existing Person => 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.

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Thanks for your reply, could you please tell me how the model first achieve that goal? – James Jun 05 '12 at 09:26
  • Hi, @Ladislav Mrnka, any ideas? – James Jun 06 '12 at 03:38
  • Model first will not create table splitting for you. It would require changing the generation process to identify one-to-one relation and create single table for related entities. That would be quite complex change. – Ladislav Mrnka Jun 06 '12 at 07:56