Thursday, May 24, 2018

Configure One-to-Many Relationships in EF 6 using the code-first approach.

Here, we will learn how to configure One-to-Many relationships between two entities (domain classes) in Entity Framework 6.x using the code-first approach.Let's configure a one-to-many relationship between the following Order and Customer entities where there can be many students in one grade.

public class Order
{
    public int OrderId { get; set; }
    
}
       
public class Customer 
{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
    
}
The one-to-many relationship can be configured in the following ways.
  1. By following Conventions
  2. By using Fluent API Configurations
In this topi i will cover only Conventions Part.

Convention 1:

We want to establish a one-to-many relationship between the Order and Customer entities where many students are associated with one Customer. It means that each Order entity points to a Customer. This can be achieved by including a reference navigation property of type Customer in the Order entity class, as shown below.
public class Order
{
    public int OrderId { get; set; }    
    public Customer Customer { get; set; }
}

public class Customer
{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
    
}
In the above example, the Order class includes a reference navigation property of Customer class. So, there can be many Orders in a single Customer. This will result in a one-to-many relationship between the Order and Customer table in the database.

Convention 2:

Another convention is to include a collection navigation property in the principal entity as shown below.

public class Order
{
    public int OrderId { get; set; }
    
}

public class Customer
{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
    
    public ICollection<Order> Orders { get; set; } 
}

In the above example, the Customer entity includes a collection navigation property of type ICollection<Order>. This also results in a one-to-many relationship between the Order and Customer entities. 

Convention 3:

Including navigation properties at both ends will also result in a one-to-many relationship, as shown below.

public class Order
{
    public int Id { get; set; }
    
    public Customer Customer { get; set; }
}

public class Customer
{
    public int CustomerID { get; set; }
    public string CustomerName { get; set; }
   
    
    public ICollection<Order> Order { get; set; }
}

In the above example, the Order entity includes a reference navigation property of the Customer type and the Customer entity class includes a collection navigation property of the ICollection<Order> type which results in a one-to-many relationship. 

Thank you All Hope my this blog increase you knowledge.
Please comment if you want something else.

No comments:

Post a Comment