What is AutoMapper?
AutoMapper is a .NET library that does only on thing but it does it exceptionally well. It copies data from one object to another. this kind of moving and manipulating data from one object to another is frequently occurring process in well-architected systems.
Automapper is used extensively in MVC controller classes where domain objects (DTOs) are copied to ViewModel objects and vice versa.Auto mapper keeps you from having to code it by hand which saves time and it keeps your code concise and clean.
there are the steps need to set up automapper in asp.net core.
Step 1: Create a ASP.NET core MVC web application. once you created, Run the application and make sure everything working.
Step 2: You need to add two Nuget packages to work in asp.net core.
I) Automapper II) AutoMapper.Extensions.Microsoft.DependencyInjection (nuget package)
First go to your asp.net core application , click on Dependencies -> right click, Manage Nuget Package.Install below to packages into your project.
AutoMapper.Extensions.Microsoft.DependencyInjection package contains an C# extension method to add the AutoMapper interface to Asp.Net Core DependencyInjection Container, so the object will be injected into the controller.
Step 4: Add AutoMapper to Asp.Net core DI container.
go to StartUp.cs file, ConfigureServices method.
Add services.AddAutoMapper(typeof(Startup)) after services.AddMvc()
Step 4: Add two object one Domain entity and ViewModel object as below for testing.
Create Artist Domain Entity model.
public class Artist
{
public Artist() { }
public int? Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Country { get; set; }
public string Description { get; set; }
public IEnumerable Artists { get; set; }
}
Artist ViewModel Class:
public class ArtistViewModel : BaseViewModel
{
public ArtistViewModel(){ }
public int? Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string LifeSpan { get; set; }
public string Description { get; set; }
public IEnumerable Artists { get; set; }
}
Step 5: Configure AutoMapper to use in ASP.NET MVC Controller
public class HomeController : BaseController
{
private readonly IMapper _mapper;
public HomeController(IMapper mapper)
{
_mapper = mapper;
var configuration = new MapperConfiguration(cfg =>
{
cfg.CreateMap();
cfg.CreateMap();
});
_mapper = configuration.CreateMapper();
}
public IActionResult Index()
{
//_mapper.Map
If you want to more information, click
local_offer Posted in .NET account_box