简体   繁体   中英

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:

当前的联结表结构

Thank you.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM