Using Auto Mapper in asp.net web MVC / api

Ahad Arif
3 min readApr 10, 2020

--

Step by Step Simple Approach of Applying Data Transfer Object in asp.net web mvc 5 / web API 2 Entity Framework 6 DB First/ Code First

Why we should use Data Transfer Object?

  1. We Use DTO or Data Transfer objects for Decoupling our app from directly being connected to entity data model.
  2. DTO gives additional security and Flexibility in our code.
  3. We Can Change easily our object-relational mapping framework such as entity framework to any another framework.

What Are The Best Practices of using Data Transfer Object?

we must send DTO to our client side and receive DTO from our client side . Our Entity Data Model object Should Never be exposed to our client directly.

How can DTO be used in our MVC/Web Api 2 project ?

  1. Manually
  2. Using Automapper

Implementation :

our database Diagram, (I keep it as simple as possible)

step 1: Install auto-mapper from NuGet package manager

install automapper in your project

step 2: Add Entity Framework ( DB first/code first ) data Models .

(this will be covered in separate blog) , for simplicity I assume that you know how to implement EF 6 from a desired database.

step 3 : Entity Data Model will be like this,

“Post” Table Entity (DB first approach)
“Comments” Table Entity (DB first approach)

Step 4:create DTO(data transfer object) from entity-framework entities

Data Transfer Object for post
Data Transfer Object for comments

Step 5: Add MappingProfile.cs Class inside App_Start folder

Mapping Profile Defines which class to match with whom for automapping.

Step 6: Add below code in Global.asax inside Application_Start() method

Step 7: Now you can apply conversation like this in your MVC controller/API controller

converting list of Entity object into list of DTO .

List of object conversation

Converting single object

single Object conversation

--

--