Phil Sandler
Phil Sandler

Reputation: 28016

Mapping 1 to 0-1 In Entity Framework

Doing Entity Framework (5) code first, although we are not generating our data model from the code--we just keep them in sync manually (less of a pain than it sounds).

Trying to create a 1 to 0-1 relationship. Here is the setup using a made-up example of a customer that could have 0 or 1 address:

Edit: original example was not right. Customer can have 0-1 Addresses, Address has exactly 1 customer. Table design and code both updated.

Address
--------------
AddressId (identity)
AddressText
CustomerId (Edit: this employs a unique constraint)
Customer
--------------
CustomerId (identity)
CustomerName

Relevant part of Address mapping:

   this.HasKey(t => t.AddressId);
   //SEE NOTE ON THIS BELOW
   //this.Property(t =>t.AddressId).
                   HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
   this.HasRequired(t => t.Customer)
       .WithOptional();

Relevant part of Customer mapping:

  this.HasKey(t => t.CustomerId);
   this.HasOptional(b => b.Address)
            .WithRequired(); 

Note the line commented out in Customer. If I include this, I get the following error:

A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'CustomerId'.

If I don't include it, I get:

Cannot insert explicit value for identity column in table 'Customer' when IDENTITY_INSERT is set to OFF.

I have searched high and low, and the code above seems to be the recommended approach. I have also seen some vague mention that 1:1 relationships can't be modeled unless the two tables share a key of the same name?

Can this sort of relationship be modeled in code, and if so, what is the correct syntax?

Upvotes: 2

Views: 1666

Answers (1)

devdigital
devdigital

Reputation: 34349

Your mapping looks invalid. You are saying that an Address has an optional Customer, and a Customer has a required address, but your Address foriegn key on your Customer entity is nullable, so the relationship should be the other way around.

Also, yes, if you want to model a 1 to 1 relationship, then you should have a Customer table with a primary key, and then an Address table with a primary key column which is also a foreign key to your Customer table.

Otherwise, you are really modelling a one-to-many relationship in the database.

Upvotes: 3

Related Questions