Entity Framework vs NHibernate

Facebook
Twitter
LinkedIn

Never miss a post!

Sign up for our newsletter and get FREE Development Trends delivered directly to your inbox.

You can unsubscribe any time. Terms & Conditions.
Categories

In this article, we are going to cover the major differences between Entity Framework and NHibernate frameworks. Entity Framework is an open source Object Relational Model (called as ORM), which provides the features of accessing the data from various data sources like SQL, PostgreSQL. NHibernate is an open source relational model, which maps the domain specific objects. Read the differences between NHibernate and Entity Framework. It . 

What is Entity Framework?

Entity Framework is an open source Object Relational Model to help you in accessing records and perform crud operations on database. It also helps in mapping entities to domain specific objects, thus providing you to write less code to handle database layer. It provides features to work with .NET framework. It stores the data from the properties of domain entity to the database and fetches the record from the database in the related business entities. It can work easily with all the modern databases such as MySQL, SQLite, Azure Cosmos and PostgreSQL.

Entity Framework was released in the version of .NET Framework 3.5 with two advanced workflows i.e. model-first and database-first. After the first version, continuous improvements were made in the framework and the concept of lazy loading, Plain Old CLR Objects (aka. POCO), self-tracking entities and template generator were introduced in version 4. The code-first development was introduced in version 4.3. Table-valued functions, enumerated types were added in version 4.5 Version 6 added asynchronous operations, stored procedures for CRUD operations in the Entity Framework. After version 6, .NET Core version was released with the more advanced features such as DbContext Pooling, self-contained configuration classes. Connection resiliency, shadow properties, etc.

What is NHibernate?

NHibernate allows you to map domain objects to traditional databases. It works closely with database layer and Plain CLR Objects (POCO). We had NHibernate approach available before the release of Entity Framework. It is a part of Hibernate from Java.

NHibernate has gone through a series of changes over the period. Version 1 was introduced with the basic features and later generics were included as a minor release to the original release. It stopped supporting .NET Framework 1.x in version 2. Later, version 3 was introduced with Language Integrated Query (LINQ) and QueryOver, lazy loading was also included in the same version. Some advancements were made in the series of version 3.x such as Hibernate Query Language (HQL), mapping of views from databases, bytecode generator etc. It started supporting .NET Framework 4 with the induction of version 4. Later, asynchronous operations, transaction scope and major advancements were introduced in version 5. Version 5.1 is introduced to support .NET Core framework.

Platforms

Entity Framework was introduced with the .NET framework 3.5; therefore, it supports all the versions after 3.5. With the introduction of .NET Core framework, EF Core was also introduced to support it. It can work with relational model and any kind of data source.

NHibernate 4 supports .NET 4 and the higher versions. It supports all the platforms where Mono is available such as Windows. It only supports relational databases and cannot support other data sources.

Architecture

Entity Framework is made on the top of ADO.NET features and in the latest version of .NET Core, it supports the .NET Core features like built-in Dependency Injection and Logging.

In NHibernate framework, systems are also designed to work with layered architecture. It does not support Dependency Injection but there are ways to achieve it, as it is not extensible as Entity Framework is.

Configurations and Mappings

Entity Framework uses code first approach (fluent) configuration and attribute based mapping. It can map public and non-public properties or fields and supports shadow properties as well.

NHibernate has both fluent and XML configurations and mappings. It also supports attribute based mapping by using the NHibernate Attributes. You can also use conventions, which is an additional gain of NHibernate since Entity Framework Core does not support it until now. In this framework, you can have shadow properties, which are not a part of class model but present in the database.

SQL Query and CRUD Operations

Entity Framework has the ability to parse SQL queries to fetch the data from the connected database. It allows you write strong typed queries by using the dbcontext class of the referenced table.

NHibernate can support multiple pathways to write queries, which includes LINQ, HQL, Query Over, Criteria API and SQL method. It can use stored procedure and custom SQL query to perform any operation. They both are capable of doing asynchronous operations for querying and modifications.

Caching

Entity Framework supports first level caching i.e. it is only available during the lifetime of a transaction. You can cache the result of the selected queries.

NHibernate supports first and second level of caching through distributed cache provider which includes ASP.NET Cache, NCache, Redis, SysCache, etc.

Validation

Entity Framework uses Data Annotations that can validate the entities by adding one or more attributes to the properties in it.  It can be applied on any entity class or a property to override the default behavior.

Let us take an example of Student class having custom data attributes.

[Table("tblStudents")]
public class Student {

   [Key]
   public int StudentID { get; set; }
   [Required]
   public string FirstName { get; set; }
   [Required]
   public string LastName { get; set; }
   public DateTime DateOfBirth{ get; set; }
	
   public virtual ICollection SubjectEnrollmentList { get; set; }
}

NHibernate uses NHibernate Validator to perform validations or you can use a legacy approach i.e. by implementing interfaces. Let suppose you want to validate the first and last name of student, you can write something like given below:


public class StudentValidator : ValidationDef
{
    public StudentEmployeeValidator()
    {
        Define(x => x.FirstName).IsValid();
        Define(x => x.LastName).IsValid();
        Define(x => x.FullName).NotNullable(); 
    }
}

Entity Framework with LINQ

LINQ or Language Integrated Query allows writing queries that are transformed into native SQL command and execute the database statement. It has three layered architecture, the upper layer or the top most layer contains language extensions and the lo level or bottom layer has data sources.

Let us take an example of Entity Framework with LINQ example, in which you can fetch a list of student who are enrolled in Computer Science department. It is recommended to use using statement as it goes out of scope automatically after executing the statement.

using DataAccess;
using System;
using System.Linq;

namespace EFTestApplication 
{
   public class Program 
   {
      public static void Main(string[] args ) 
      {
          // create an instance of dbcontext class by using command
          using ( var dbCntext = new SchoolDBEntities() )
          {
              var query = dbCntext.Students
                       .Where( s => s.StudentName == "Computer Science " )
                       .FirstOrDefault ();
          }
       }
   }
}

NHibernate with LINQ

You can use LINQ provider in NHibernate framework with the help of the following two syntax given below:

  • Query Chaining Syntax
  • Query Comprehension Syntax

Query Chaining Syntax

Let us have a look at the following example in which you can retrieve the list of students who are enrolled in Business Studies department.


using System; 
using System.Data; 
using System.Linq; 
using System.Reflection; 

// include NHibernate namepsaces
using HibernatingRhinos.Profiler.Appender.NHibernate; 
using NHibernate.Dialect; 
using NHibernate.Criterion; 
using NHibernate.ConfigObj; 
using NHibernate.Driver; 
using NHibernate.Linq;

namespace NHibernateTestApplication { 

   public class Program {
	
      private static void Main() { 
		
         var configObj = ConfigureNHibernate(); 
         var sessionFactory = configObj.BuildSessionFactory();
         using ( var session = sessionFactory.OpenSession() ) {
         
         using( var txnObj = session.BeginTransaction() ) {
            var student = session.Query()
.Where( s => s.DepartmentName == "Business Studies " ).First(); 
            Console.WriteLine( student ); 
            txnObj.Commit(); 
         }
        }		
         Console.WriteLine(" Press any key to exit... "); 
         Console.ReadLine(); 
      }
		
      private static Configuration ConfigureNHibernate() { 
		
         NHibernateProfiler.Initialize(); 
         var configObj = new Configuration(); 
         
         configObj.DataBaseIntegration( x => { 
            x.ConnectionStringName = "default" ; 
            x.Driver() ; 
            x.Dialect() ; 
            x.IsolationLevel = IsolationLevel.RepeatableRead ; 
            x.Timeout = 10 ; 
            x.BatchSize = 10 ; 
         }); 
         
         configObj.SessionFactory().GenerateStatistics();
         configObj.AddAssembly(Assembly.GetExecutingAssembly()); 
         return configObj; 
      } 
   } 
}

Query Comprehension Syntax

Let us have a look at the following example in which you can retrieve the list of students who are enrolled in Business Studies department. This syntax is more similar to SQL queries.

using NHibernate.Dialect; 
using NHibernate.Criterion; 
using NHibernate.ConfigObj; 
using NHibernate.Driver; 
using NHibernate.Linq;

namespace NHibernateTestApplication { 

   public class Program { 
	
      private static void Main() { 
		
         var configObj = ConfigureNHibernate(); 
         var sessionFactory = configObj.BuildSessionFactory();
         using ( var session = sessionFactory.OpenSession() ) 
         
         using ( var txnObj = session.BeginTransaction() ) {
            var student = ( from s in session.Query() 
               where s.FirstName == "Business Studies " select s ).First();
            Console.WriteLine( student ); 
            txnObj.Commit();
         }
         
         Console.WriteLine(" Press any key to exit ... "); 
         Console.ReadLine(); 
      }
      
      private static Configuration ConfigureNHibernate() {
		
         NHibernateProfiler.Initialize(); 
         var configObj = new Configuration(); 
         
         configObj.DataBaseIntegration(x => { 
            x.ConnectionStringName = "default" ; 
            x.Driver(); 
            x.Dialect() ; 
            x.IsolationLevel = IsolationLevel.RepeatableRead; 
            x.Timeout = 10 ; 
            x.BatchSize = 10 ; 
         }); 
         
         configObj.SessionFactory().GenerateStatistics() ;
         configObj.AddAssembly( Assembly.GetExecutingAssembly() ); 
         return configObj; 
      } 
   } 
}

Summary

Entity Framework and NHibernate are open source object relational mapping model frameworks. They are used to map domain related entities to the database schema without writing data access code for the connected database.

Facebook
Twitter
LinkedIn

Our website uses cookies that help it to function, allow us to analyze how you interact with it, and help us to improve its performance. By using our website you agree by our Terms and Conditions and Privacy Policy.