EF链接表有3个外键

时间:2015-07-17 18:31:36

标签: c# entity-framework

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

for(var i = 0; i < getFields.length; i++) {
    console.log(getFields[i]);
}

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

[User] 
UserId

[Association]
AssocId

[Role]
RoleId

[LNK_User_Assoc_Role]
UserId   [PK]
AssocId  [PK]
RoleId   [FK]

2 个答案:

答案 0 :(得分:3)

有两种方法可以满足您的需求。

  1. 使用Data Annotations

    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);
    }
    

答案 1 :(得分:0)

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;}
}