Code First .

There are models of Product and User . A user can have many products purchased online and many purchased offline. At the same time, the product has a list of users who purchased online and a list of offline, respectively.

It turns out we have 2 connections many to many. How to implement it in classes of models?

 public class Product { public int Id { get; set; } public int Price { get; set; } public virtual ICollection<User> OnlineCustomers { get; set; } public virtual ICollection<User> OfflineCustomers { get; set; } } public class User { public int Id { get; set; } public string Name { get; set; } public virtual ICollection<Product> OnlinePurchases { get; set; } public virtual ICollection<Product> OfflinePurchases { get; set; } } 

As far as I know, with many to many connections, EF automatically creates a third table, calling it ProductUsers . But if there are two links, how will additional tables be named? And how can you change the naming rule for intermediate tables, which attribute or Fluent API?

    1 answer 1

    Fluent API

     protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Product>() .HasMany(q => q.OnlineCustomers) .WithMany(q => q.OnlinePurchases) .Map(q => { q.ToTable("OnlineProductUsers"); q.MapLeftKey("ProductId"); q.MapRightKey("UserId"); }); modelBuilder.Entity<Product>() .HasMany(q => q.OfflineCustomers) .WithMany(q => q.OfflinePurchases) .Map(q => { q.ToTable("OfflineProductUsers"); q.MapLeftKey("ProductId"); q.MapRightKey("UserId"); }); } 

    In total there will be 4 tables: Product, User, OnlineProductUsers, OfflineProductUsers

    Data Annotations

     public class Product { public int Id { get; set; } public int Price { get; set; } [InverseProperty("OnlinePurchases")] public virtual ICollection<User> OnlineCustomers { get; set; } [InverseProperty("OfflinePurchases")] public virtual ICollection<User> OfflineCustomers { get; set; } } public class User { public int Id { get; set; } public string Name { get; set; } public virtual ICollection<Product> OnlinePurchases { get; set; } public virtual ICollection<Product> OfflinePurchases { get; set; } } 

    The disadvantage is that EF will come up with the names of the new tables.

    There will be 4 tables in total: Product, User, ProductUsers, ProductUser1

    • In this case, are the classes of models indicated in the question left as they are? Do you need to change anything? - tretetex
    • if you use the Fluent API, the model classes are left as is. If you want to use data annotations, you can use the InverseProperty attribute - Ruslan_K
    • Understood thanks! - tretetex