Entity Framework Core Many to Many Relationships

In order to add a many to many relationship between 2 of your context models you will need to do a few things differently than a one to one or one to many relationship.

You can’t just add navigation properties to each class and let EF take care of the rest. You will need to also add some custom code in your Context class.

Lets use the example of Orders and Products. An order can have many products and a product can have many orders – many to many!

In a normal database we would need an intermediary table to link the two – let’s call it ProductOrders (or OrderProducts).

Our code will look something like this:

public class Product
{
 public int Id { get; set; }
 public ICollection<ProductOrder> ProductOrders { get; set; }
}

public class Order
{
 public int Id { get; set; }
 public ICollection<ProductOrder> ProductOrders { get; set; }
}

public class ProductOrder
{
 public int ProductId { get; set; }
 public Product Product{ get; set; }

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

Inside your DbContext class:

public DbSet<Order> Orders { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<ProductOrder> ProductOrders { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ProductOrder>()
 .HasKey(t => new { t.ProductId, t.OrderId });

modelBuilder.Entity<ProductOrder>()
 .HasOne(pt => pt.Product)
 .WithMany(p => p.ProductOrders)
 .HasForeignKey(pt => pt.ProductId);

modelBuilder.Entity<QuoteGrant>()
 .HasOne(pt => pt.Order)
 .WithMany(t => t.ProductOrders)
 .HasForeignKey(pt => pt.OrderId);
}

written on 13/04/2016 – Entity Framework Core is still in RC stage so might have changed since then.

  • Dubyna Oleksandr

    hi. how use this for save data?