Automapper in .NET Core

Aman Singh Parihar
2 min readMay 3, 2021

--

We will create a project in .NET Core using dotnet cli and will use visual studio code as the IDE.

Go to any directory where you want to create this project.

We are using powershell to setup this project.

PS E:/VSCODE/NETProjects>mkdir Automapper
PS E:/VSCODE/NETProjects>cd Automapper

Lets create a solution in Automapper folder.

PS E:/VSCODE/NETProjects>Automapper>dotnet new sln

Lets create a project in the Automapper folder.

PS E:/VSCODE/NETProjects>Automapper>dotnet new webapi -o Automapper.API

Lets add the project in the solution file because as of now they are disconnected to each other.

dotnet sln add Automapper.API/Automapper.API.csproj

Now lets open Automapper folder in vscode.

PS E:/VSCODE/NETProjects>Automapper>code .

Switch to project folder and install automapper.

PS E:/VSCODE/NETProjects>Automapper>cd Automapper.APIPS E:/VSCODE/NETProjects>Automapper>Automapper.API>dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection

We setup our project, now lets write some code. First of all delete the weather api controller and weather api class as we don’t need this.

Lets create two folders Models and DTO.
Models will have classes that will exactly match with the database tables and DTO will have classes which need to pass to the client.

In our case we are using Employee class in Models folder and EmployeeDTO in DTO folders.

Employee.cs

EmployeeDTO.cs

You can see that we are not passing employee salary to the client.

Now we will create profile which will map from Employee to EmployeeDTO.

Lets create a folder AutoMapperProfile in the project and add a class AutomapperProfile.cs.

AutomapperProfile.cs

Lets setup the ConfigureServices method of startup class for automapper.

Startup.cs

EmployeeController.cs

We are almost done with this, lets run this project and see the output.

PS E:/VSCODE/NETProjects>Automapper>Automapper.API>dotnet run

Type this url in the browser to view the output:

https://localhost:5001/api/Employee

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Aman Singh Parihar
Aman Singh Parihar

Written by Aman Singh Parihar

I work as a software engineer and having experience in web technologies. I like to share my knowledge with the community and aspire to learn cool things.

No responses yet