Handling Parent Child SQL Table relation using Fluent NHibernate


Ahamed Fazil Buhari
SharePoint Developer
Published On :   29 Nov 2017
Visit Count
Today :  1    Total :   103
Plan, Migrate, Secure, Report
SharePoint & Office 365 Tool. Simple & Easy to Use. 15-Day Trial!

Sharegate: Kick-Ass Tool
Think Your SharePoint & Office 365 Are Secure ? Find Out Now!


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)
                             .AsSet()
                             .Inverse()
                             .Cascade.All();
   }
      }
     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.

 TablePackage.cs
 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; }
     }
 ChildTable.cs
 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.

 <parent-data>
 <ID>xxx</ID>
 <Status>xxx</Status>
 <CreationDate>xxx</CreationDate>
 <Child>
 <Name></Name>
 <Age></Age>
 <Child>
 <Child>
 <Name></Name>
 <Age></Age>
 <Child>
 </parent-data>
 

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

Happy Coding

Ahamed

SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Categories

Migratiin Tools for SharePoint