C#C
C#3w ago
Yarden

I'm trying to implement many-to-many relationship inside my database. Not sure what to do next.

I have 3 tables already:
Users, Coffeeshop and UserCoffeeShops for the many-to-many relationships.

I already added the necessary code:
Inside dbContext:
 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
     modelBuilder.Seed(); //A side method to add the constraints

     //Creation of many-to-many relationship:
     modelBuilder.Entity<UserEntity>()   
         .HasMany(x => x.CoffeeShops)    //  Specifies that a User can have many Coffee shops.
         .WithMany(x => x.Users)         //  Specifies that a Coffee shop can have many Users.       
         .UsingEntity(j => j.ToTable("UserCoffeeShops")); //  Explicitly names the join table. (If I don’t specify this, EF Core will)
 }

Inside CoffeeShopEntity:
    public ICollection<UserEntity> Users { get; } = [];// Navigation property for many-to-many

Inside User entity:
        public ICollection<CoffeeShopEntity> CoffeeShops { get; set; } = []; // Navigation property for many-to-many


I already have existing users and coffeeshops.
The question is how I suppose to connect between them and add them to the table of UserCoffeeshops?
image.png
Was this page helpful?