如何引用不引用主键列的外键。 Asp.net 首先是mvc代码?

How to reference foreign key which does not reference a primary key column. Asp.net mvc code first?

我在另一个 table 中引用了我的一个列(不是主键)作为外键。但我不确定如何在 Entity Framework 中处理它。我有特殊原因无法将我的主键用作参考 table.

中的外键列
public class Users : IUser
{
    [Key]
    [StringLength(64)]
    [Column("USERID")]
    public string USERID { get; set; }

    [StringLength(128)]
    public string NAME { get; set; }
    [Column("PASSWORD")]
    [MaxLength(64)]
    public byte[] PASSWORD { get; set; }

    [StringLength(2)]
    public string STATUS { get; set; }

    [Column("UserIdentifierId")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
}

public class RolesUsers
{
    [Key]
    public int RolesUsersId { get; set; }
    public int UserId { get; set; }
    public int RoleId { get; set; }
    [ForeignKey("UserId")]
    public virtual Users User { get; set; }
    [ForeignKey("RoleId")]
    public virtual Roles Role { get; set; }
}

如您所见,UserIdentifierId 是我在 RolesUsers table 中为 UserId 配置的专栏(在 SQL UserIdentifierId为唯一约束,可供参考)

我现在收到以下错误:

One or more validation errors were detected during model generation: RolesUsers_User_Target_RolesUsers_User_Source: : The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role. The type of property 'UserId' on entity 'RolesUsers' does not match the type of property 'USERID' on entity 'Users' in the referential constraint 'RolesUsers_User'.

SQL结构:

CREATE TABLE [dbo].[ATQ_USERS]
(
    [USERID] [varchar](64) NOT NULL,
    [NAME] [varchar](128) NULL,
    [PASSWORD] [varbinary](64) NULL,
    [STATUS] [char](2) NULL,
    [UserIdentifierId] [int] IDENTITY(1,1) NOT NULL,

    CONSTRAINT [PK_ATQ_USERS] 
        PRIMARY KEY CLUSTERED ([USERID] ASC)) ON [PRIMARY],
    CONSTRAINT [Uk_UserIdentifierId] 
        UNIQUE NONCLUSTERED ([UserIdentifierId] ASC)) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

CREATE TABLE [dbo].[Roles]
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](200) NULL,
    [IsActive] [bit] NOT NULL,
    [CreatedOnUTC] [datetime] NULL,
    [UpdatedOnUTC] [datetime] NULL,
    [DeletedOnUTC] [datetime] NULL,
    [IsDeleted] [bit] NOT NULL,
    [Text] [varchar](50) NULL,

    CONSTRAINT [PK_dbo.Roles] 
        PRIMARY KEY CLUSTERED ([Id] ASC)
) ON [PRIMARY]

CREATE TABLE [dbo].[RolesUsers]
(
    [RolesUsersId] [int] IDENTITY(1,1) NOT NULL,
    [RoleId] [int] NULL,
    [UserId] [int] NULL,

    PRIMARY KEY CLUSTERED ([RolesUsersId] ASC)
) ON [PRIMARY]

GO
ALTER TABLE [dbo].[RolesUsers] WITH CHECK 
    ADD FOREIGN KEY([RoleId]) REFERENCES [dbo].[Roles] ([Id])
GO

ALTER TABLE [dbo].[RolesUsers] WITH CHECK 
    ADD FOREIGN KEY([UserId]) REFERENCES [dbo].[ATQ_USERS] ([UserIdentifierId]) 

没问题。只需将 UserIdentifierId 声明为实体键即可。在数据库中将哪个密钥声明为 PK 并没有什么神奇之处。您的实体可以使用任何唯一索引作为键。