EF链接表有3个外键

本文关键字:3个 链接表 EF | 更新日期: 2023-09-27 18:03:11

用户可以访问多个关联。对于给定的用户,我需要为他可以访问的每个关联分配一个工作角色。我如何首先在EF代码中映射表?

[User] 
UserId
[Association]
AssocId
[Role]
RoleId
[LNK_User_Assoc_Role]
UserId   [PK]
AssocId  [PK]
RoleId   [FK]

更新:我认为octavioccl是正确的,但我如何分配Assoc给用户?这是我的代码。它不愿意工作:

_user = new USER();
_user.Username = user.Username
DbContext.USERS.Add(_user);
DbContext.SaveChanges();
var newUser = DbContext.USERS.Find(_user.User_Id);                                               
foreach (int assocId in select2)
{
LNK_UserRoleAssoc u = new LNK_UserRoleAssoc();                           
u.User = newUser;
u.Association = DbContext.Associations.Find(assocId);
u.Role = DbContext.ROLES.Find(2);
newUser.UserRoleAssocs.Add(u);                          
}
DbContext.SaveChanges();

EF链接表有3个外键

有两种方法可以达到你所需要的。

  1. 使用数据注释:

    public class User{
      [Key]
      public Guid UserId {get;set;}
      public virtual ICollection<UserRoleAssociation> UserRoleAssociations {get;set;}      
    }
    public class Role{
      [Key]
      public Guid RoleId {get;set;}
      public virtual ICollection<UserRoleAssociation> UserRoleAssociations {get;set;}
    }
    public class Association{
      [Key]
      public Guid AssociationId {get;set;}
      public virtual ICollection<UserRoleAssociation> UserRoleAssociations {get;set;}
    }
    public class UserRoleAssociation{
     [Key,ForeignKey("User"),Column(Order=1)]
     public Guid UserId {get;set;}
     [Key,ForeignKey("Role"),Column(Order=2)]
     public Guid RoleId {get;set;}
     [Key,ForeignKey("Associoation"),Column(Order=3)]
     public Guid AssociationId {get;set;}
     //Navigation Properties
     public virtual User User {get;set;}
     public virtual Role Role {get;set;}
     public virtual Association Association {get;set;}
    

    }

  2. 使用Fluent Api。在这种情况下,您不需要在我上面显示的模型中使用任何属性(删除它们),只需在您的上下文中覆盖OnModelCreating方法并添加这些配置:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
     base.OnModelCreating(modelBuilder);
     modelBuilder.Entity<UserRoleAssociation>()
        .HasKey(c => new {c.UserId, c.RoleId, c.AssociationId});
     modelBuilder.Entity<UserRoleAssociation>()
        .HasRequired(p => p.User)
        .WithMany(u => u.UserRoleAssociations)
        .HasForeignKey(p => p.UserId);
     modelBuilder.Entity<UserRoleAssociation>()
        .HasRequired(p => p.Role)
        .WithMany(r => r.UserRoleAssociations)
        .HasForeignKey(p => p.RoleId);
     modelBuilder.Entity<UserRoleAssociation>()
        .HasRequired(p => p.Association)
        .WithMany(a => a.UserRoleAssociations)
        .HasForeignKey(p => p.AssociationId);
    }
    

EF将根据对象之间的关系生成FK。

public class User{
    public Guid UserId {get;set;}
    public Role Role {get;set;}
    public Association Association {get;set;}
}
public class Role{
    public Guid RoleId {get;set;}
}
public class Association{
    public Guid AssociationId {get;set;}
}