Nhibernate Self Reference uni-directional

In my previous post we have seen to implement self reference (Bi-directional) . Today we will quickly see  how to achieve self reference uni-directional.

Scenario

Lets take a simple scenario of a tree structure . One node can have many Children nodes but any child node will have only one parent.

Node.cs

NodeMap.cs

Now  we do not have any mapping table because we want it unidirectional mapping. In database we have only one table Node . Lets see how to get  complete tree now ..

Above mapping will create the below realtion

You can refer below link for more details :

http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/05/14/how-to-map-a-tree-in-nhibernate.aspx

You can download complete implementation from here

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. 🙂