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


Advertisements

6 thoughts on “Nhibernate : Self reference to an object using Fluent Nhibernate

  1. Hi,
    I’m a bit confused. Would you keep both these classes in your project? The business object class, and the domain model class? It would be nice to hear some discussion around that. I can see how m:m maps in a bi-directional class references are present; We have both Employee.Managers, and Manager.Employees. But what if the class references are uni-directional?

    1. I think you understand m:m mapping in the above piece of code. Now you want the same Uni-directional

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

      You can also have a look on the sample code also :
      http://hibernatingrhinos.googlecode.com/svn/trunk/TreeStructure/

      If you still have some problem to understand/implement the scenario you want, please share your problem. I believe we will be able to find a s0lution for it.

      Have nice day.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s