1

我有一个 MS-SQL 表,如下所示。

用户表

CREATE TABLE [dbo].[Users]( 
[UserId] [uniqueidentifier] NOT NULL    Primary Key,
[UserAccount] [nvarchar](50) NOT NULL       Unique,
[Password] [nvarchar](50) NOT NULL,
[UserEmail] [nvarchar](50) NOT NULL,
[JoinDate] [datetime2](7) NOT NULL,
[LoginDate] [datetime2](7) NULL)

角色表

CREATE TABLE [dbo].[Roles](
[RoleId] [uniqueidentifier] NOT NULL    Primary Key,
[RoleName] [nvarchar](50) NOT NULL      Unique,
[Note] [nvarchar](50) NOT NULL,
[RegistDate] [datetime2](7) NOT NULL)

UsersInRoles 表

CREATE TABLE [dbo].[UsersInRoles](
[UserId] [uniqueidentifier] NOT NULL,
[RoleId] [uniqueidentifier] NOT NULL,
[SetDate] [datetime2](7) NOT NULL,
PRIMARY KEY CLUSTERED (
[UserId] ASC,
[RoleId] ASC)WITH (
PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]
GO

ALTER TABLE [dbo].[UsersInRoles]  WITH CHECK ADD FOREIGN KEY([RoleId]) REFERENCES [dbo].[Roles] ([RoleId]) GO
ALTER TABLE [dbo].[UsersInRoles]  WITH CHECK ADD FOREIGN KEY([UserId]) REFERENCES [dbo].[Users] ([UserId]) GO

我试图在 EF Code-First 中表达这一点。

用户实体类

public class User
{
    public Guid UserId { get; set; }
    public string UserAccount { get; set; }
    public string Password { get; set; }
    public string UserEmail { get; set; }
    public DateTime JoinDate { get; set; }
    public DateTime LoginDate { get; set; }
}

角色实体类

public class Role
{
    public Guid RoleId { get; set; }
    public string RoleName { get; set; }
    public string Note { get; set; }
    public DateTime RegistDate { get; set; }
}

UsersInRole 实体类

public class UsersInRole
{   
    public Guid UserId { get; set; }
    public Guid RoleId { get; set; }
    public DateTime SetDate { get; set; }
}

外键的问题,应该如何设计UsersInRoles?

如果有更好的设计,请告诉我。

4

2 回答 2

0

如果您正在设计数据库然后使代码符合要求,那么这并不是真正的代码,是吗?听起来您应该在您的 User 类上定义一个角色集合,然后让 EntityFramework 完成构建该中间表的工作。它将处理 FK 关系。

于 2013-04-16T03:04:25.313 回答
0

我没有尝试运行以下代码,所以我不能 100% 确定。但是我会从...开始

在您的域类中

public class User
{
 public Guid UserId { get; set; }
 public string UserAccount { get; set; }
 public string Password { get; set; }
 public string UserEmail { get; set; }
 public DateTime JoinDate { get; set; }
 public DateTime LoginDate { get; set; }
}

public class Role
{
 public Guid RoleId { get; set; }
 public string RoleName { get; set; }
 public string Note { get; set; }
 public DateTime RegistDate { get; set; }
}


public class UsersInRole
{   
 public DateTime SetDate { get; set; }
 virtual User User { get; set; }
 virtual Role Role { get; set; }
}

在您的上下文中,您需要

public DbSet<Role> Roles { get; set; }

public DbSet<User> Users { get; set; }

public DbSet<UsersInRole> UsersInRoles { get; set; }

可选地,您可能想要包括

public virtual  ICollection<UsersInRole> Roles { get; private set; } 

在用户类中

和/或

public virtual  ICollection<UsersInRole> Users { get; private set; } 

在角色类中将保持相同的数据结构。

于 2013-04-16T04:25:28.210 回答