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:

Querying Entity Model. Part 12 – Unpivot

LINQ allows you to create both pivot and unpivot queries to the Entity Framework model. For this experiment I have a table with 6 columns: OperationDate and five columns Op1Result… Op5Result. Now I want to unpivot data to get a regular tables as it was in my previous post Querying Entity Model. Part 11 – Pivot

Unpivot operation can be made with two LINQ queries. First query will split table into separate result entities (rows). The second query will unite all rows into the regular table.

Entity Framework generates two SQL queries.

The second query has a rather bad execution plan. 5 table scans and 4 distinct sort operations are just for 5 columns to be unpivoted. I expect it will degrade when the number of columns would raise.

Unpivot execution plan