2

我有一个看起来像这样的数据库:

tblUsers
   - UserId
tblRoles
   - RoleId

tblUserRoles
   - UserRoleId
   - RoleId
   - UserId

class User
{
   [Key]
   public virtual int UserId{ get; set; }

   [ForeignKey("UserId")] // how does this tell ef not to map it to the primary key. 
                             It needs to map to UserId which is not defined as a key.??

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

class UserRoles
{
   [Key]
   public virtual int UserRoleId{ get; set; }

   public virtual int UserId{ get; set; }
   public virtual int RoleId{ get; set; }

   [ForeignKey("RoleId")]
   Public Role RoleInfo {get; set;}
}

class Role 
{
   [Key] 
   public virtual int RoleId {get; set;}

   public string RoleName {get; set;}
}

我不认为这是正确的。我需要设置外键不是主键而是表中的列的模型。我的问题:如何在没有主键的情况下定义我的模型并链接实体之间的关系?

4

2 回答 2

3

你不需要声明类UserRoles,EF代码首先会创建幕后需要的关系和表,这就是你所需要的:

public class User
{
    public int Id {get;set;}
    public virtual ICollection<Role> Roles {get;set;}
}

public class Role
{
    public int Id {get;set;}
    public virtual ICollection<User> Users {get;set;}
}

然后覆盖你的OnModelCreating

protected override void OnModelCreating(DbModelBuilder builder)
{
    builder.Entity<User>()
    .HasMany(u => u.Roles).WithMany(r => r.Users)
    .Map(t => t.MapLeftKey("UserId")
    .MapRightKey("RoleId")
    .ToTable("UserRoles"));
}

唯一需要自己声明连接表的情况是,如果您需要many-to-many带有有效负载。使用有效负载多对多检查此帖子

于 2013-06-03T21:51:48.907 回答
2

您的意思是如何将这些表链接在一起?我通常有我的模型设置来镜像(大部分)数据库的表结构。下面是我将如何设置模型。User有一个集合,UserRoles每个集合都有一个Role与该记录。

internal class User
{
    public User()
    {
        UserRoles = new List<UserRole>();
    }

    [Key]
    public int UserId { get; set; }

    public ICollection<UserRole> UserRoles { get; set; }
}

internal class UserRole
{
    [Key]
    public int UserRoleId { get; set; }

    public int UserId { get; set; }
    public int RoleId { get; set; }

    [ForeignKey("UserId")]
    public User User { get; set; }

    [ForeignKey("RoleId")]
    public Role Role { get; set; }
}

internal class Role
{
    public Role()
    {
        UserRoles = new List<UserRole>();
    }

    [Key]
    public int RoleId { get; set; }

    public string RoleName { get; set; }

    public ICollection<UserRole> UserRoles { get; set; }
}

所以基本上用户和之间存在一对多,和UserRole之间存在一对多RoleUserRole

于 2013-06-03T21:50:51.203 回答