Creating many, many connection tables in the Entity Framework

I try to add a lot to the many relationships between my two entities. I need a connection table with an additional field, I know that EF cannot do this automatically and that I need to create an Entity for my connection 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 the user to have permission stored in the connection table. Therefore, I 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 mine, OnModelCreatingI also added the following (probably I'm wrong)

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

This works to some extent, I can successfully add user / provider / permissions to this table.

But I cannot add the same user / provider several times to this table (perhaps due to PK?).

, ?

:

Current junction table structure

.

+4
1

, UserId SupplierId , ?

SupplierUsersId ProviderUsers .

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; } 
}

OnModelCreating()

+4

Source: https://habr.com/ru/post/1538430/


All Articles