Handling Parent Child SQL Table relation using Fluent NHibernate

Ahamed Fazil Buhari
Senior Developer
Published On :   29 Nov 2017
Visit Count
Today :  2    Total :   1470

Title: Handling Parent Child SQL Table relation using Fluent NHibernate

Hello everyone,

This article is continuation of my previous article – “Configuration of Fluent NHibernate through C# code”. Here we can see how to do mapping of parent and child relation with the help of primary and foreign key concept in SQL. We can achieve it with the help of Fluent NHibernate.

To create child table we need to update Mapping class –

 TableMapping.cs – Mapping class should extend ClassMap<> FluentNHibernate class
 using FluentNHibernate.Mapping;
     public class TableMapping : ClassMap<TablePackage>
         public TableMapping()
             Id(x => x.ID).GeneratedBy.Assigned();//.GeneratedBy.Increment();
             Map(x => x.Status);
             Map(x => x.CreationDate);
      // One to May relation
      HasMany(x => x.ChildTable)
     public class ChildMapping : ClassMap<ChildTable>
         public ChildMapping()
             Id(x => x.TempId).GeneratedBy.Increment();
             Map(x => x.Name);
             Map(x => x.Age);
             //Use References to create relationship with Parent;
             References(x => x.TablePackage).Cascade.All();

And in the Domain layer, define ChildTable structure and child table reference in Parent table.

 public class TablePackage
         public virtual string ID { get; set; }     
         public virtual string Status { get; set; }
         public virtual DateTime CreationDate { get; set; }
  public virtual ICollection<ChildTable> ChildTable { get; set; }
 public class ChildTable
         public virtual string TempId { get; set; }       
         public virtual TablePackage TablePackage { get; set; }
         public virtual string Name { get; set; }
  public virtual int Age { get; set; }

If we receive the message in the below format, then it will save data in two different table with parent child relation.


In the next article we will see how to save and get the data using Fluent Nhibernate.

Happy Coding