我有一个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?

请让我知道是否有更好的设计。

===============>>#1 票数:0

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

===============>>#2 票数: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; } 

在User类中

和/或

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

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

  ask by user2214027 translate from so

未解决问题?本站智能推荐: