8

Let's say you have two tables, "Users" and "UserRoles". Here's how the two tables are structured (table - columns):

Users - UserID (int)

UserRoles - UserID (int), Role (string)

What I want is for my "User" class in my domain to have an IList of roles. How do I construct my Fluent NHibernate mapping to achieve this?

Kevin Pang
  • 41,172
  • 38
  • 121
  • 173

4 Answers4

13

What you're looking for is a of a set of elements, which in standard hbm mapping is:

<set name="Roles" table="UserRoles">
  <key column="UserID" />
  <element column="Role" />
</set>

For Fluent NHibernate you can map this like so:

HasMany<string>(x => x.Roles)
  .AsElement("Role");

You may need to also specify the key name using WithKeyColumn(string).

James Gregory
  • 14,173
  • 2
  • 42
  • 60
4

FWIW this has change minorly of present day. The current mapping is

HasMany<string>(x => x.Roles)
  .Element("Role");
Chris Marisic
  • 32,487
  • 24
  • 164
  • 258
0

I beleive it would be

public User()
  {
    Id(x => x.UserID);
    HasMany<UserRoles>(x => x.UserRoles).AsBag();
  }

You'll also have to make sure you map your UserRoles class as well

lomaxx
  • 113,627
  • 57
  • 144
  • 179
  • The thing is UserRoles isn't a class. It's just a list of strings. The datatable isn't linking two foreign keys, just one foreign key (UserID) and a role name (string). – Kevin Pang Jan 11 '09 at 18:57
0

This also worked:

HasMany<Role>(u => u.Roles)
                .WithTableName("UserRoles")
                .Component(role => role.Map(r => r.Name))
                .AsList();

You don't need to map Role or UserRoles.

Make sure Role implements IEquatable < Role > ;.

Assaf Lavie
  • 73,079
  • 34
  • 148
  • 203