December 23, 2019

Using AutoMapper with ASP.Net Core MVC 3.0

Need to map between view models and database models? Simon Gilbert explains a performant way of doing this using AutoMapper in C# Asp.Net Core MVC 3.0

Using AutoMapper with ASP.Net Core MVC 3.0

Models vs. View Models

Occasionally you will require the ability to separate a model for a view, from the equivalent model for a database. But what happens when you need to transfer the view model data to the database model object?

Enter "AutoMapper"

AutoMapper is an object-object mapper, and makes this mapping task fairly straight-forward (albeit, following some configuration).

AutoMapper

Implementation Steps

  • Install a copy of "AutoMapper.Extensions.Microsoft.DependencyInjection" from Nuget.
AutoMapper with ASP.Net Core MVC 3.0
  • Create a view model.
AutoMapper with ASP.Net Core MVC 3.0
  • Create a model.
AutoMapper with ASP.Net Core MVC 3.0
  • Create an AutoMapper "Profile" (class which inherits from the Profile class in AutoMapper), for defining the map between the view model and the model.
AutoMapper with ASP.Net Core MVC 3.0
  • Configure Services in Startup.cs to add AutoMapper to the project.
AutoMapper with ASP.Net Core MVC 3.0
  • Create a service for executing the model mapping.
AutoMapper with ASP.Net Core MVC 3.0
  • Configure Services in Startup.cs for your mapping service (as a transient service).
AutoMapper with ASP.Net Core MVC 3.0

Download Github Code Sample

Feel free to DOWNLOAD the sample code of the aforementioned implementation from my Github account.