One to one relationships have a reference navigation property on both sides. They follow the same conventions as one-to-many relationships, but a unique index is introduced on the foreign key property to ensure only one dependent is related to each principal.
C#Copy
publicclassBlog
{
publicint BlogId { get; set; }
publicstring Url { get; set; }
public BlogImage BlogImage { get; set; }
}
publicclassBlogImage
{
publicint BlogImageId { get; set; }
publicbyte[] Image { get; set; }
publicstring Caption { get; set; }
public int BlogId { get; set; } public Blog Blog { get; set; }
}
Note
EF will choose one of the entities to be the dependent based on its ability to detect a foreign key property. If the wrong entity is chosen as the dependent, you can use the Fluent API to correct this.
When configuring the relationship with the Fluent API, you use the HasOne and WithOne methods.
When configuring the foreign key you need to specify the dependent entity type - notice the generic parameter provided to HasForeignKey in the listing below. In a one-to-many relationship it is clear that the entity with the reference navigation is the dependent and the one with the collection is the principal. But this is not so in a one-to-one relationship - hence the need to explicitly define it.