Work With Fluent NHibernate In Core 2.0

NHibernate is an object-relational mapping (ORM) framework, it allow you to map the object oriented domain model with the tables in a relational Database. To realize the mapping, we have to write XML mapping files (.hbm.xml files), and to make it easier, here comes Fluent NHibernate as an abstraction layer to do it in C# rather than XML.

Introduction

NHibernate is an object-relational mapping (ORM) framework, it allows you to map the object-oriented domain model with the tables in a relational database. To realize the mapping, we have to write XML mapping files (.hbm.xml files), and to make it easier, here comes Fluent NHibernate as an abstraction layer to do it in C# rather than XML.

Databases supported by NHibernate include:

  • SQL Server
  • SQL Server Azure
  • Oracle
  • PostgreSQL
  • MySQL
  • SQLite
  • DB2;
  • Sybase Adaptive Server
  • Firebird
  • Informix

It can support even the use of OLE DB (Object Linking and Embedding) and even ODBC (Open Database Connectivity)

What makes NHibernate stronger than Entity Framework is that it integrates querying API set like LINQ, Criteria API (implementation of the pattern Query Object), integration with Lucene.NET, use of SQL even stored procedures.

NHibernate also supports:

  • Second Level Cache (used among multiple ISessionFactory).
  • Multiple ways of ID generation such as Identity, Sequence, HiLo, Guid, Pooled even Native mechanism used in databases.
  • Flushing properties (FlushMode properties in ISession that can take these values: Auto or Commit or Never).
  • Lazy Loading.
  • Generation and updating system like migration of API in Entity framework. (Like Code First).

When Microsoft started working on the Framework Core, much functionality in NHibernate wasn’t supported in .NET Core as a target platform, but from the version Core 2.0, we can integration NHibernate even Fluent NHibernate.

NuGet package

The NuGet package to use Fluent NHibernate,

PM>  Install-Package FluentNHibernate -Version 2.1.2

Create Entities

This folder will include two entities: Person and Task.

Person Entity
  1. public class Person {  
  2.     public virtual int Id {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public virtual string Name {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public virtual DateTime CreationDate {  
  11.         get;  
  12.         set;  
  13.     }  
  14.     public virtual DateTime UpdatedDate {  
  15.         get;  
  16.         set;  
  17.     }  
  18. }  
Task Entity
  1. public class Task {  
  2.     public virtual string Id {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public virtual string Title {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public virtual string Description {  
  11.         get;  
  12.         set;  
  13.     }  
  14.     public virtual DateTime CreationTime {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public virtual TaskState State {  
  19.         get;  
  20.         set;  
  21.     }  
  22.     public virtual Person AssignedTo {  
  23.         get;  
  24.         set;  
  25.     }  
  26.     public virtual DateTime CreationDate {  
  27.         get;  
  28.         set;  
  29.     }  
  30.     public virtual DateTime UpdatedDate {  
  31.         get;  
  32.         set;  
  33.     }  
  34.     public Task() {  
  35.         CreationTime = DateTime.UtcNow;  
  36.         State = TaskState.Open;  
  37.     }  
  38. }  
  39. public enum TaskState: byte {  
  40.     /// <summary>  
  41.     /// The task is Open.  
  42.     /// </summary>  
  43.     Open = 0,  
  44.         /// <summary>  
  45.         /// The task is active.  
  46.         /// </summary>  
  47.         Active = 1,  
  48.         /// <summary>  
  49.         /// The task is completed.  
  50.         /// </summary>  
  51.         Completed = 2,  
  52.         /// <summary>  
  53.         /// The task is closed.  
  54.         /// </summary>  
  55.         Closed = 3  
  56. }  
Create Mappings

This folder will contain the mapping classes for the previous entities.

PersonMap
  1. public class PersonMap: ClassMap < Person > {  
  2.     public PersonMap() {  
  3.         Id(x => x.Id);  
  4.         Map(x => x.Name);  
  5.         Map(x => x.CreationDate);  
  6.         Map(x => x.UpdatedDate);  
  7.     }  
  8. }  
TaskMap
  1. public class TaskMap: ClassMap < Task > {  
  2.     public TaskMap() {  
  3.         Id(x => x.Id);  
  4.         Map(x => x.CreationTime);  
  5.         Map(x => x.State);  
  6.         Map(x => x.Title);  
  7.         Map(x => x.Description);  
  8.         Map(x => x.UpdatedDate);  
  9.         Map(x => x.CreationDate);  
  10.         References(x => x.AssignedTo);  
  11.     }  
  12. }  
Create the SessionFactory Builder

In the folder SessionFactories, we will include the class of SessionFactoryBuilder that will manage the schema builder and SessionFactory builder.

  1. public class SessionFactoryBuilder {  
  2.     //var listOfEntityMap = typeof(M).Assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(M))).ToList();  
  3.     //var sessionFactory = SessionFactoryBuilder.BuildSessionFactory(dbmsTypeAsString, connectionStringName, listOfEntityMap, withLog, create, update);  
  4.     public static ISessionFactory BuildSessionFactory(string connectionStringName, bool create = false, bool update = false) {  
  5.         return Fluently.Configure().Database(PostgreSQLConfiguration.Standard.ConnectionString(ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString))  
  6.             //.Mappings(m => entityMappingTypes.ForEach(e => { m.FluentMappings.Add(e); }))  
  7.             .Mappings(m => m.FluentMappings.AddFromAssemblyOf < NHibernate.Cfg.Mappings > ()).CurrentSessionContext("call").ExposeConfiguration(cfg => BuildSchema(cfg, create, update)).BuildSessionFactory();  
  8.     }  
  9.     /// <summary>  
  10.     /// Build the schema of the database.  
  11.     /// </summary>  
  12.     /// <param name="config">Configuration.</param>  
  13.     private static void BuildSchema(Configuration config, bool create = false, bool update = false) {  
  14.         if (create) {  
  15.             new SchemaExport(config).Create(falsetrue);  
  16.         } else {  
  17.             new SchemaUpdate(config).Execute(false, update);  
  18.         }  
  19.     }  
  20. }  
Create Services

This folder will include all different treatments that we can do like GetAll element of an Entity, and add a new element in the database. For example, in this sample, I will include two services according to our entities.

PersonService
  1. public class PersonService {  
  2.     public static void GetPerson(Person person) {  
  3.         Console.WriteLine(person.Name);  
  4.         Console.WriteLine();  
  5.     }  
TaskService
  1. public class TaskService {  
  2.     public static void GetTaskInfo(Task task) {  
  3.         Console.WriteLine(task.Title);  
  4.         Console.WriteLine(task.Description);  
  5.         Console.WriteLine(task.State);  
  6.         Console.WriteLine(task.AssignedTo.Name);  
  7.         Console.WriteLine();  
  8.     }  
  9. }  
Add and display Table content

Now, we will try to display data from the database or add a new element.

In the program, we will start by creating a session factory using the method: BuildSessionFactory implemented inside the class SessionFactoryBuilder. After, we will open a new Session for every Transaction completed. We start a new Transaction inside, and it depends on the operation. If  we need to insert a new line in the database, we use session.SaveOrUpdate(MyObjectToAdd); after we commit this using this transaction: transaction.Commit();

  1. static void Main(string[] args) {  
  2.     // create our NHibernate session factory  
  3.     string connectionStringName = "add here your connection string";  
  4.     var sessionFactory = SessionFactoryBuilder.BuildSessionFactory(connectionStringName, truetrue);  
  5.     using(var session = sessionFactory.OpenSession()) {  
  6.         // populate the database  
  7.         using(var transaction = session.BeginTransaction()) {  
  8.             // create a couple of Persons  
  9.             var person1 = new Person {  
  10.                 Name = "Rayen Trabelsi"  
  11.             };  
  12.             var person2 = new Person {  
  13.                 Name = "Mohamed Trabelsi"  
  14.             };  
  15.             var person3 = new Person {  
  16.                 Name = "Hamida Rebai"  
  17.             };  
  18.             //create tasks  
  19.             var task1 = new Task {  
  20.                 Title = "Task 1", State = TaskState.Open, AssignedTo = person1  
  21.             };  
  22.             var task2 = new Task {  
  23.                 Title = "Task 2", State = TaskState.Closed, AssignedTo = person2  
  24.             };  
  25.             var task3 = new Task {  
  26.                 Title = "Task 3", State = TaskState.Closed, AssignedTo = person3  
  27.             };  
  28.             // save both stores, this saves everything else via cascading  
  29.             session.SaveOrUpdate(task1);  
  30.             session.SaveOrUpdate(task2);  
  31.             session.SaveOrUpdate(task3);  
  32.             transaction.Commit();  
  33.         }  
  34.         using(var session2 = sessionFactory.OpenSession()) {  
  35.             //retreive all tasks with person assigned to  
  36.             using(session2.BeginTransaction()) {  
  37.                 var tasks = session.CreateCriteria(typeof(Task)).List < Task > ();  
  38.                 foreach(var task in tasks) {  
  39.                     TaskService.GetTaskInfo(task);  
  40.                 }  
  41.             }  
  42.         }  
  43.         Console.ReadKey();  
  44.     }  
  45. }  
  46. }  

Conclusion

This sample is a sample use of Fluent NHibernate. In my next article, I will show you another web sample using some of the advantages like Criteria APIs.