Entity Framework VS Dapper. Side by side comparison

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

This article covers the famous ORM frameworks, Entity Framework and Dapper, how they work, their advantages, disadvantages, and the summary of their usage.

What is Entity Framework?

Entity Framework is an open-source Object Relational Mapping framework for Microsoft applications. It provides you to access LINQ queries, perform crud operations, and migration of schemas. It provides the following types of approaches that can be used before starting an application depending on whether the database is already established, or it is going to be a domain drive application.

  • Code First Approach

In Code First approach, the focus is on the domain of the application by creating the classes rather than designing the database and then creating the matching classes. It is also called as Domain-Driven Design. All the database operations can be performed through the code and if there is any manual change on the database, it must be replicated on the code side as well otherwise the changes will be lost once the code updates the database.

  • Database First Approach

In Database First approach, the database designing is done first then the entity framework can attach with the database. If the database is already available, then the entity framework can be used to create POCO entities or model classes based on the database tables and columns, and the classes will be the bridge between the controller and the database. It is an alternative to the Code First approach where schema is available and entity framework will be used after that. In this case, the manual modifications will remain intact and will not be changed and the same must be apply to the application code.

What is Dapper?

Dapper is a simple Object Relational Mapper to map the database to the business domain objects. It is a library provided by the NuGet Manager for .NET applications. It is also called as King of ORM in terms of the speed and is fast as raw ADO.NET Data Reader. It is faster than Entity Framework as it allows you to write raw queries as well unlike Entity Framework. It does not provide the full features of an ORM and that is the reason it is also called as ‘’Micro ORM” but the querying and updating the database is possible through raw SQL. It allows you to pass the IEnumerable list and it will parametrize the query. It can work across all the database platforms such as Microsoft SQL, SQL Lite, Oracle, MySQL, and PostgreSQL etc., as it has no specific implementations and has an ability to support stored procedures as well.

How Entity Framework Works?

Entity Framework involves a four-step process, which is given here as a high-level overview:

  • Step # 1:
    Maps classes to Database Schema
  • Step # 2:
    Translate the queries from LINQ to SQL for the execution
  • Step # 3:
    Track the changes
  • Step # 4:
    Save all the changes to the database

How Dapper Works?

Dapper involves a three-step process, which is given here in an abstract manner:

  • Step # 1:
    Create an IDBConnection object with the Connection String
  • Step # 2:
    Write a query to perform CRUD operations and store it in a string
    variable
  • Step # 3:
    Call the db.execute() method and pass the above query in it and it is
    done

Entity Framework Architecture

Entity Framework has the following components as a part of its architecture:

  • Data Providers

It translates LINQ to native SQL expressions and execute the commands.

  • Entity Data Model

The first component of Entity Framework is an Entity Data Model. It is an in-memory representation of the whole model. It consists of three parts

  • Conceptual Model

It consists of the model classes and the relationships among them. This is an independent model from the database schema design.

  • Mapping

It is responsible for the information of mapping the conceptual model to the storage model.

  • Storage Model

It is the representation of the database design such as tables, views,
relationships with the keys, and stored procedures.

  • Object Services

It is responsible to manage the session between the applications and the data source.

Example


private static void AddCustomer () {
   using (var context = new CustomerContext() ) {
      var customer = new Customer {
         FirstName = "John", 
         LastName = "Terry", 
         DOB = "2000-01-10",
         EmailAddress = "[email protected]", 
         RegisterDate = DateTime.Parse("2021-07-23") 
      } ;
      context.Customer.Add(customer); 
      context.SaveChanges();
   }
}

Dapper Architecture

Dapper is a library that is available in NuGet that can be added in the
project, and it will extend the IDBConnection interface implementation. It
works directly with the IDBConnection interface and provides an option of
early or late bindings. It has three helpers that can be used for mapping
the result:

  • Mapping of Results to a Strongly Typed List

You can execute a query and map the results directly to a strongly typed
list with the help of the following code:


public class Animal
{
    public Guid AnimalID { get; set; }
    public int? Age { get; set; }
    public string AnimalName { get; set; }
    public float? Weight { get; set; }
    public int IgnoredProperty { get { return 1; } }
}

var guid = Guid.NewGuid();
var animalObject = connection.Query(" select AnimalID = @AnimalID", Age = @Age, 
new { Age = (int?)null, AnimalID = guid });

Assert.Equal( 1, animalObject.Count() );
Assert.Null( animalObject.First().Age );
Assert.Equal( guid, animalObject.First().AnimalID );

  • Mapping of Results to a Dynamic Typed List

You can execute a query and map the results directly to any dynamic typed
list with the help of the following code:

var dynamicRows = connection.Query(“select 1 X, 2 Y union
all select 3, 4 “).AsList();Assert.Equal(1, (int) dynamicRows [0].X );Assert.Equal(2, (int) dynamicRows [0].Y );Assert.Equal(3, (int) dynamicRows [1].X );Assert.Equal(4, (int) dynamicRows [1].Y );
  • Command with no Mapping

You can still execute a query that does not produce any results to be
mapped with the help of the following code:

var count = connection.Execute( @"
  set nocount on
  create table #temp (i int)
  set nocount off
  insert #temp
  select @x x union all select @y
  set nocount on
  drop table #temp", new { x = 1, y = 2 } );
Assert.Equal(2, count );

Advantages of Entity Framework

  • Entity Framework provides an option of creating the model classes by writing programming code or by using Entity Framework designer, from which a new database can be generated.
  • Entity Framework can produce objects from the code and has an ability to track the changes on those objects.
  • The common syntax LINQ is used to write queries which is easy to use and implement. The system can achieve high complex tasks with the help of it.
  • Entity Framework can generate the code automatically generally for doing CRUD operations.
  • Entity Framework also reduced the development time and effort of the programmers by having an auto generated code.
  • Entity Framework allows you to do the mapping and design models visually.

Advantages of Dapper

  • There are no specific requirements as it work with every database.
  • It allows you to write parameterized queries correctly.
  • It can easily execute all types of queries such as scalar, multi-grids, multi-rows etc.
  • It is easy to convert the result into objects in Dapper.
  • It is very efficient and called as a King of ORM when you talk about the performance.

Disadvantages of Entity Framework

  • In Entity Framework, if there is any change in the database schema, then
    the change needs to be done in the schema manually as it will not reflect
    automatically.
  • The query is controlled by the provider and cannot be changed.
  • The main drawback of Entity Framework is lazy loading.

Disadvantages of Dapper

  • The biggest disadvantage of Dapper is that it cannot generate a class
    model automatically.
  • It cannot track the objects and the changes related to it.
  • There is no provision of doing CRUD operations in raw dapper library, however, the contrib library can be used as an additional package to perform the CRUD operations.

Summary

An ORM or Object Relational Mapping is an object-oriented programming technique that is used to map data between two incompatible types. Dapper is called as the micro ORM as it does not provide the full functionality and features like Entity Framework does. Dapper provides you an ability to fetch the data from a relational database. It does not support code first support approach and can work with the querying and update through raw SQL. It cannot be used to configure classes and has a set of extension methods for ADO.NET. Entity Framework is an open source ORM that is available as a part of .NET framework. It is responsible to handle the interactions
between the relational databased and .NET applications. It simplifies the programming code by generating the model classes for the database schema automatically. It allows you to have the database first and create the entities from it or alternatively, the application code can be initiated before the designing of database. In this way, any manual changes to the database, needs to be updated or copied to the code level because the changes will be lost.

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.