简体   繁体   中英

Fluent NHibernate ManyToMany with Reference Table

After take several solution about manytomany mapping i cannot make this thing works
I have these tables :

User:  
intID (PK)  
vcUsername

Role:  
intID (PK)  
vcDescription

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

here is my class :

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

and here is my class map:

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

when i run, i get this error at startup
The entity 'UserRole' doesn't have an Id mapped

how do i map this manytomany properly, with insert and update work properly? i hope your guide clearly.. thanks

It should probably be this instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM