在实体框架创建多对多的结表 [英] Creating many to many junction table in Entity Framework

查看:201
本文介绍了在实体框架创建多对多的结表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个多添加了许多关系的两个实体我之间。我需要一个路口表的附加字段,我知道这意味着EF不能自动做这做那,我需要为我的结表创建一个实体。

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.

我有以下型号

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

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

在我的 OnModelCreating 我还添加以下(这可能是我要去哪里错了)

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.

但是我不能多次添加同一用户/供应商这个表(可能是由于PK?)。

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:

感谢您。

推荐答案

如果我理解正确的话要将多个等于对用户ID和供应商ID添加到SupplierUsers,对吧?

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

一SupplierUsersId字段添加到您SupplierUsers实体,并使其主键。

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



卸下OnModelCreating(配置)

Remove the configuration from OnModelCreating()

这篇关于在实体框架创建多对多的结表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆