One-To-Many And One-To-One Relationship In Code First Model

It’s very simple to create a one-to-many relationship between entities in Code First model. Just place ICollection<T2> at “one” end of the relationship, and T1 at the “many” end.

The result is shown in the following diagram. EF creates new field for the foreign key, the name is autogenerated in the form Entity_Key (in my case, Client_Id).
one-to-many diagram

In order to convert this relationship to one-to-one (yeah, Entity Framework allows you to do this), it seems that it’s enough to change ICollection to Phone. But EF throws an error:

Unable to determine the principal end of an association between the types 'Clients.Phone' and 'Clients.Client'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

It means you need to explicitly mark one end of the relationship as Required attribute.

But EF won’t create a field for foreign key, it uses the primary key of Phone entity to be the foreign key too.
one-to-one diagram

The same action can be achieved by adding ForeignKey attribute before primary key field instead a Required. So my Phone class will look like this:

Leave a Reply

Your email address will not be published. Required fields are marked *