Given I have two entities: Deputy and DeputyProfile:
public class Deputy : IdableEntity
{
[Required]
public string FirstName { get; set; }
public string Patronimic { get; set; }
[Required]
public string LastName { get; set; }
}
public class DeputyProfile : IdableEntity
{
[Required]
public string Dosieur { get; set; }
}
is the best way to establish a one-to-one relationship between them is by placing navigation property from DeputyProfile to Deputy (childe to parent) or visa-verse?
Should it be like this?:
public class DeputyProfile : IdableEntity
{
[Required]
public virtual Deputy Deputy{ get; set; }
[Required]
public string Dosieur { get; set; }
}
What is the logical rule based on which it is best to make that decision?
P.S. Being a child of IdableEntity gives a class its own Guid Id field.
You must choose a Principal (parent) end and a Dependent (child) side for any relation. You are free to choose whichever you like best. To me the Deputy seems the clear Principal as it is likely to have many more relations as your model grows.
A one to one relation is implemented by a shared primary key; the DeputyProfile must have as its primary key the Deputy ID. That will make your code like this:
Note: As it is implemented now every Deputy must have a profile. If the profile is optional make the ProfileID an ‘int?’.
I can heartily recommend this excellent series of blogs about implementing relations in the Entity Framework 4.1 and higher