Handling Parent Child SQL Table relation using Fluent NHibernate

Ahamed Fazil Buhari
 
Senior Developer
November 29, 2017
 
Rate this article
 
Views
4186

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

Author Info

Ahamed Fazil Buhari
 
Senior Developer
 
Rate this article
 
Ahamed is a Senior Developer and he has very good experience in the field of Microsoft Technologies, especially SharePoint, Azure, M365, SPFx, .NET and client side scripting - JavaScript, TypeScript, ...read more
 

Leave a comment