流畅的NHibernate ManyToMany与参考表

时间:2013-08-05 14:23:19

标签: c# nhibernate fluent-nhibernate mapping many-to-many

关于多种映射的几个解决方案后,我无法使这个东西工作 我有这些表:

User:  
intID (PK)  
vcUsername

Role:  
intID (PK)  
vcDescription

UserRole:  
intID (PK-FK)  
intRole (PK-FK)  
btActive

这是我的班级:

public class User {
  public virtual int Id {get; set;}
  public virtual string Username {get;set;}
  public virtual IList<UserRole> Roles {get; set;}
}

public class Role {
  public virtual int Id {get; set;}
  public virtual string Description {get;set;}
  public virtual IList<UserRole> Users {get; set;}
}

public class UserRole {
  public virtual User User {get; set;}
  public virtual Role Role {get;set;}
  public virtual bool IsActive {get; set;}
}

这是我的班级地图:

public UserMap() {
  Table("tb_user");
  Id(f => f.Id).Column("intID").GeneratedBy.Native();
  Map(f => f.Username).Column("vcUsername").Not.Nullable();
  HasMany(f => f.Roles).KeyColumn("intID").LazyLoad().Inverse().Cascade.All();
}

public RoleMap() {
  Table("tb_role");
  Id(f => f.Id).Column("intID").GeneratedBy.Native();
  Map(f => f.Description).Column("vcDescription").Not.Nullable();
  HasMany(f => f.Roles).KeyColumn("intRole").LazyLoad();
}

public UserRoleMap()
{
  Table("tb_user_role");
  References(f => f.User).Column("intID").Not.Nullable();
  References(f => f.Role).Column("intRole").Not.Nullable();
  Map(f => f.IsActive).Column("btActive").Not.Nullable();
}

当我跑步时,我在启动时收到此错误 The entity 'UserRole' doesn't have an Id mapped

如何正确地映射这个多个,插入和更新工作正常? 我希望你的导游清楚..谢谢

1 个答案:

答案 0 :(得分:0)

应该是这样:

public UserRoleMap()
{
  Table("tb_user_role");
  CompositeId()
            .KeyReference(x => x.User, "intID")
            .KeyReference(x => x.Role, "intRole");
  Map(f => f.IsActive).Column("btActive").Not.Nullable();
}