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

{

Table(“Users”);

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

Map(x => x.FirstName);

Map(x => x.LastName);

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

.ParentKeyColumn(“UserID”)

.ChildKeyColumn(“GroupID”);

Map(x => x.CreatedOn);

}

}

Group Mapping

public class UserGroupMap :ClassMap

{

public UserGroupMap()

{

Table(“Groups”);

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

Map(x => x.Value);

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

.ParentKeyColumn(“GroupID”)

.ChildKeyColumn(“UserID”);

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 .

Advertisements

Nhibernate : Self reference to an object using Fluent Nhibernate

BusinessObject

Public Class Employee

{

public virtual  int Id {get; set;}

public virtual  string Name {get; set;}

public virtual  string Address {get; set;}

}
Domain Model :

Public Class Employee

{

public virtual  int Id {get; set;}

public virtual  string Name {get; set;}

public virtual  string Address {get; set;}

Public IList<Employee> Managers {get;set;}

}

Scenario :1

One employee can have more than one Manager , Manager is also an employee . Fluent Nhibernate takes care of the self-reference of the object .Here in the business model we have the many-to-many relationship.

But in this Domain Model Employee object has  self-reference .

Solution :1

Mapping :

Public class EmployeeManagermap : ClassMap

{

Public EmployeeManagermap()

{

Id(x => x.Id,”EmployeeId”);

map(x=> x.Name ,”EmployeeName”);

HasManyToMany(x => x.Managers)

.ParentKeyColumn(“EmployeeId”)

.ChildKeyColumn(“ManagerID”)

.Table(“EmployeeManagers”);

}

}


The above mapping will create a Table EmployeeManagers which will have two columns EmployeeId and ManagerId.

That’s it .

Hope this help to someone  . If you face some problem to implement any Nhibernate mapping scenario , you can contact me. 🙂