Asp.net Ef核心外键唯一,这不是我想要的

Asp.net Ef核心外键唯一,这不是我想要的,asp.net,entity-framework,Asp.net,Entity Framework,我试图将导航属性添加到userprivilege模型中,但问题是我希望导航属性(用户和权限)不是唯一的,或者至少在一个唯一的外键中加入它们 以下是我的userprivilege模型: public class UserPrivilege { public int ID { get; set; } public int UserID { get; set; } public int PrivilegeID { get; set; } public virtual

我试图将导航属性添加到userprivilege模型中,但问题是我希望导航属性(用户和权限)不是唯一的,或者至少在一个唯一的外键中加入它们

以下是我的userprivilege模型:

public class UserPrivilege
{
    public int ID { get; set; }
    public int UserID { get; set; }
    public int PrivilegeID { get; set; }

    public virtual User User { get; set; }
    public virtual Privilege Privilege { get; set; }
}
这是我的特权模型

public class Privilege
{
    public int ID { get; set; }
    public string Title { get; set; }

    public virtual UserPrivilege UserPrivilege { get; set; }
}
以下是我的用户模型:

public class User
{
    public int ID { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }

    public virtual UserPrivilege UserPrivilege { get; set; }
    
}

PS:我希望能够从user和privilege访问UserPrivilege属性,以及从UserPrivilege类访问user和privilege属性。

您必须修复这些类

public class Privilege
{
    public int ID { get; set; }
    public string Title { get; set; }

  public virtual ICollection<User> Users { get; set; }
    public virtual ICollection<UserPrivilege> UserPrivileges { get; set; }
}


public class User
{
    public int ID { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }

    public virtual ICollection<Privilege> Privileges { get; set; }
    public virtual ICollection<UserPrivilege> UserPrivileges { get; set; }
}
公共类特权
{
公共int ID{get;set;}
公共字符串标题{get;set;}
公共虚拟ICollection用户{get;set;}
公共虚拟ICollection用户权限{get;set;}
}
公共类用户
{
公共int ID{get;set;}
公共字符串电子邮件{get;set;}
公用字符串电话{get;set;}
公共虚拟ICollection权限{get;set;}
公共虚拟ICollection用户权限{get;set;}
}
如果您决定使用一对多而不是多对多,则必须删除UserPriviledge类并更改另外两个类

public class User
{
    public int ID { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }

    public int? PrivilegeId { get; set; }
    public virtual Privilege Privilege { get; set; }
  
}
public class Privilege
{
    public int ID { get; set; }
    public string Title { get; set; }

    public virtual ICollection<User> Users { get; set; }
}
````
公共类用户
{
公共int ID{get;set;}
公共字符串电子邮件{get;set;}
公用字符串电话{get;set;}
public int?PrivilegeId{get;set;}
公共虚拟特权{get;set;}
}
公共阶级特权
{
公共int ID{get;set;}
公共字符串标题{get;set;}
公共虚拟ICollection用户{get;set;}
}
````

谢谢@Serge,但问题是我希望userprivilege对于用户来说是唯一的o null。用户有一个特权(等级)。但我想我明白我犯的错误是从哪里来的,谢谢!那么为什么要创建一个表UserPriviledge呢?你是对的,我在创建用户特权表时犯了一个错误(我想为我的用户自定义创建特权,并在将来给他们多个特权),但我认为目前没有必要这样做。“你认为我现在应该删除它吗?”“穆罕默德,我在我的回答中添加了另一个变体。你可以选择一个适合你需要的。谢谢,我理解我所犯的错误。这个问题应该包括更多细节并澄清问题。