Categories
c# entity-framework sql

Creating many to many junction table in Entity Framework

I am trying to add a many to many relationship between two of my entities. I need a junction table with an additional field, I’m aware that means EF cannot do this automatically and that I need to create an Entity for my junction table.

I have the following models

public class Supplier
{
public int Id { get; set;}
public virtual ICollection<SupplierUsers> UserPermissions { get; set; }
}

And

public class User
{
public string Id { get; set;}
public virtual ICollection<SupplierUsers> UserPermissions { get; set; }
}

I need for a user to have a permission stored in the junction table. So I have created the following entity

public class SupplierUsers
{
public string UserId { get; set; }
public int SupplierId { get; set; }
public SupplierUserPermission Permission { get; set; }
public virtual Supplier Supplier { get; set; }
public virtual User User { get; set; }
}

In my OnModelCreating I’ve also added the following (this is probably where I’m going wrong)

modelBuilder.Entity<SupplierUsers>()
.HasKey(x => new { x.UserId, x.SupplierId });

This works to an extent, I can successfully add a user/supplier/permission to this table.

But I cannot add the same user / supplier multiple times to this table (probably due to the PK?).

How can I alter my code so that I can add the same user or supplier multiple times in this table?

Here’s what the table structure looks like at the moment:

Current junction table structure

Thank you.