C Sharp - Automapper

Automapper

Installation

With ASP.Net Core - use the nuget package manager to install Automapper.Extensions.Microsoft.DependencyInjection

Adding into your program

Startup.CS

Adding to program

Update startup.cs

1
2
3
4
5
6
7
8
using AutoMapper;

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper(typeof(Startup));
services.AddControllers();
}

Then add classes to hold mapping information

CompanyMapping.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using AutoMapper;
using WF.Shared.Entities;
using WF.Shared.ViewModels;

namespace WF.Shared.Mappings
{
public class CompanyMapping : Profile
{
public CompanyMapping()
{
CreateMap<CompanyViewModel, CompanyEntity>()
.ReverseMap();
}
}
}

In this case, I have a CompanyViewModel, and a CompanyEntity objects. CompanyViewModel is what is exposed to the API, CompanyEntity is used for database.

Then I have methods like this

CompanyService.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
:
IResult<List<CompanyViewModel>> ICompanyService.GetAllCompanys()
{
try
{
var companyList = _companyRepository.GetAll();

if (companyList.WasSuccessful)
return new Result<List<CompanyViewModel>>(_mapper.Map<List<CompanyViewModel>>(companyList.Model)).ReturnSuccess(companyList.Message.FriendlyMessage);
else
return new Result<List<CompanyViewModel>>().ReturnFail(0, companyList.Message.FriendlyMessage);
}
catch (Exception e)
{
return new Result<List<CompanyViewModel>>().ReturnFail(0, LogError("Internal error processing the request. Please contact admin.", e));
}
}

Line 9, is where the mapper is called, this converts a list of CompanyEntity objects into a list of CompanyViewModel objects.

References: