4

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.

Alex
  • 1,549
  • 2
  • 16
  • 41

1 Answers1

4

If i understand you correctly you want to add multiple equal pairs of UserId and SupplierId to SupplierUsers, right?

Add a SupplierUsersId field to your SupplierUsers entity and make it primary key.

public class SupplierUsers
{
    public int SupplierUsersId { get;set; }
    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; } 
}

Remove the configuration from OnModelCreating()

user3411327
  • 1,031
  • 8
  • 14
  • I was sure I tried this by setting the [Key] in the SupplierUsers class, but I must have not commented out the OnModelCreating() code that related to it. Thank you! – Alex Apr 29 '14 at 01:16