Configure One-To-Many Relationships In Entity Framework Using Code First Approach

Updated: Sep 9, 2020

Introduction The relationship between tables is defined by using foreign keys in relational databases. The foreign key is a column or combination of columns which enforces a  relation between the data of two tables. The following three types of relationships are supported:

  1. One to One

  2. One to Many or Many to one

  3. Many to Many

All three type of relationships are supported by entity framework in code first approach. In this article we will cover one-to-many relationships between entities. A one-to-many relationship happens when the primary key of one table becomes foreign keys in another table and also this primary key should participate in primary key of second table. In this relationship only zero, one and more than one records are present on either side of tables.

Understand One to Many relationship To understand one-to-many relationships, I have created two entities: People and PeopleAddress. One people record has one or more Address records. Here PeopleId is primary key for People table and it also participate in primary key and foreign key of PeopleAddress table.

Through association an entity can be related to the other entities in the 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 relations 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: People POCO class:

[Table("People")]  
public partial class People  
{  
 public People()  
        {  
 this.PeopleAddress = newHashSet < PeopleAddress > ();  
        }  
        [DatabaseGenerated(DatabaseGeneratedOption.None)]  
        [Key]  
    public int PeopleId  
    {  
 get;  
 set;  
    }  
    [Required]  
    [StringLength(50)]  
    public string FirstName  
    {  
 get;  
 set;  
    }  
    [Required]  
    [StringLength(50)]  
    public string LastName  
    {  
 get;  
 set;  
    }  
    public virtual ICollection < PeopleAddress > PeopleAddress  
    {  
 get;  
 set