Save, Update and Get data from SQL using Fluent NHibernate

Ahamed Fazil Buhari
 
Senior Developer
November 30, 2017
 
Rate this article
 
Views
5833

Hello everyone,

This article is continuation of my previous two articles – “Configuration of Fluent NHibernate through C# code” and “Handling Parent Child SQL Table relation using Fluent NHibernate”. Once we configured and mapped the data, we need to save it in SQL and this is our major goal.

We can achieve bulk update easily using Fluent nhibernate and it gives very good performance. Call the below function with the list of package.

 public static void SaveOrUpdatePackage(List<TablePackage> packages)
         {        
             using (var session = _sessionFactory.OpenSession())
             {
                 using (var transaction = session.BeginTransaction())
                 {
                     session.SetBatchSize(1000);
                     foreach (var package in packages)
                     {
   //If you don’t want to update and you want only to save
   //_session.Save(package);
                        session.SaveOrUpdate(package);
                     }
                     transaction.Commit();
                 }
             }
         }
 

To get all the data from Database

 public IList<string> GetTableDetails()
         {
             using (var session = _sessionFactory.OpenSession())
             {
                 var tableIDs = session.QueryOver<TablePackage>()
 //Here we are selecting only ID, you do multiple selection as //well
                              .Select(x => x.ID)
                              .OrderBy(x => x.ID)
                              .Asc.List<string>();
                 return tableIDs;
             }
         }
 

To get data based on ID –

 public string GetTableDetailById(string ID)
         {
             using (var session = _sessionFactory.OpenSession())
             {
                 var tableValue = session.Get<TablePackage>(ID);
   //Convert table value into JSON object
                 return JsonConvert.SerializeObject(tableValue);
             }
         }
 

 

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