Configure One To One Relationship In Entity Framework Using Code First Approach

Introduction Relationship between tables is defined using foreign keys in relational database. The foreign key is a column or combination of columns which enforce relation between data of two tables. There are three types of relationships:

  1. One to One

  2. One to Many or Many to one

  3. Many to Many

All three types of relationship is supported by entity framework in code first approach. In this article we will cover one to one relationship between entities. A one to one relationship happens when the primary key of one table becomes foreign key in another table. Entity framework enforce the primary key of first table should participate in primary key of second table. In this relationship only one record or zero record is present on either side of tables. Understand One to One relationship To understand one to one relationship, I have created two entities: Employee and EmployeeDetails. One employee record has only one detail record. Here EmployeeId is primary key for Employee table and same key is present on primary key and foreign key of EmployeeDetail table.

Through an association an entity can be related to the other entities in entity framework. The relation between the entities contains two ends which describe type of the entity and multiplicity of the type. The two ends of relation can be referred as principal role and dependent role. There are two ways to configure one to one relation between two entities in Entity Framework Using DataAnnotation Entity Framework code first provides a set of data annotation attributes that can be applied on domain classes or the properties of domain classes. ForeignKey Attribute specifies the foreign key for the Navigation property in Entity Framework. As discussed earlier, a relationship in the entity framework always has two ends, a navigation property on each side and an Entity Framework that maps them together automatically by convention. If there are multiple relationships between the two entities, Entity Framework cannot handle the relationships. This is because Entity Framework doesn't know which navigation property map with which properties on other side. InverseProperty attribute can help us to resolve this issue.

Example

Employee POCO class

[Table("Employee")]  
public partial class Employee  
{  
    [DatabaseGenerated(DatabaseGeneratedOption.None)]  
    public int EmployeeId  
    {  
 get;  
 set;  
    }  
    [Required]  
    [StringLength(50)]  
    public string FirstName  
    {  
 get;  
 set;  
    }  
    [Required]  
    [StringLength(50)]  
    public string LastName  
    {  
 get;  
 set;  
    }  
    [StringLength(50)]  
    public string MiddleName  
    {  
 get;  
 set;  
    }  
    public virtual EmployeeDetail 
    {  
 get;  
 set;  
    }  
}