Fluent Nhibernate : Create Many-to-Many Relationship table

Scenario :

I have 2 objects User and Group . One User can have many Groups and , many Groups can have many users . To implement this relation , I need a UserGroupMapping table which has reference of UserID and GroupID.

UserGroup Object

public class UserGroup    {

public UserGroup()


Users = new List<Users>();


public virtual int Id { get; set; }

public virtual string Value { get; set; }
public virtual IList<Users> Users { get; set; }


Users Object

public class Users    {

public Users()


UserGroups = new List();


public virtual int Id { get; set; }

public virtual string FirstName{ get; set; }

public virtual string LastName{ get; set; }
public virtual IList UserGroups { get; set; }


User mapping

public class UsersMap:ClassMap


public UsersMap()



Id(x => x.Id,”UserID”).GeneratedBy.Identity();

Map(x => x.FirstName);

Map(x => x.LastName);

HasManyToMany<UserGroups>(x => x.Groups).Table(“UserGroupMapping“)



Map(x => x.CreatedOn);



Group Mapping

public class UserGroupMap :ClassMap


public UserGroupMap()



Id(x => x.Id,”GroupID”).GeneratedBy.Identity();

Map(x => x.Value);

HasManyToMany<Users>(x => x.Users).Table(“UserGroupMapping“)



References(x => x.CreatedBy).Not.LazyLoad();

Map(x => x.CreatedOn);

Map(x => x.UpdatedOn).Update();




Above mapping will create a table UserGroupMapping.  You can see my previous post on self reference of an object .


7 thoughts on “Fluent Nhibernate : Create Many-to-Many Relationship table

  1. Hi. Sorry for my english.
    class Group
    long Id {get;set;}
    List Users {get;set;}

    class User
    long Id {get;set;}

    and relation table “UserGroup”
    column Id;
    column GroupId;
    column UserId;

    How implement mapping?

    Thank you/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s