Relationship Mapping

In my last article we have discussed how to create entity framework and we also create one to one relationship also as every employee is having one department. In this example I want to show many to many relationship.

Create Code First Schema

Open visual studio and choose empty website. As we are not using edmx file so we have to add entity framework dll in our project. For that right click on the project and choose nugget packages.

code first approach

Choose entity framework and install it in the application

add entity framework dll

In this example I am taking customer and products. As we know a customer can buy more than one product similarly a single product can be purchased by the so many customers. It's basically many to many relationship. Following are the table schema for that.

 
public class Customer
{
    [Key]
    public int cust_id { get; set; }
    public string cust_name { get; set; }
    public List<product> prod { get; set; }
}

public class product
{
    [Key]
    public int prod_id { get; set; }
    public string prod_name { get; set; }
    public List<Customer> cust { get; set; }

}
		

To give key attribute to the classes we have to use System.ComponentModel.DataAnnotations namespace.

As we know every customer can have more than one product so I have declared prod as list of type. Similarly I have created list of customer in product table.

Now create another repository class in which we have to inherit DbContext class and need to create DbSet properties to create entities.

 
public class efRepositary:DbContext
{
   public DbSet<Customer> emps { get; set; }
    public DbSet<product> dept { get; set; }
}

		

Now go to the web.config file and add connection string

 
<connectionStrings>
    <add name="efRepositary" providerName="System.Data.SqlClient" connectionString="Data Source=ISHA;Initial Catalog=ef_relationship;User ID=isha123;Password=******;Pooling=False"/>
  </connectionStrings>


		

Now go to your default page and add product in product table

		
efRepositary ef = new efRepositary();
        ef.prod.Add(new product() { prod_name = "Shoes" });
        ef.SaveChanges();

		

Now execute the application and check your database.

output of ef

Note: - as you can to maintain many to many relationships code-first api automatically created one extra table to maintain the relationship of customer and product.