Saturday, June 6, 2020

How to Integrate AutoMapper in ASP.NET Core

What is AutoMapper ?


AutoMapper is a mapper between two objects, it means that AutoMapper is object-object mapper. It maps properties of two different Objects by transforming input object of one type to output object of another type.




Integrate AutoMapper-


Step 1-

Go to NuGet Package Manager and add package AutoMapper.Extensions.Microsoft.DependencyInjection 

Step 2-

Create two files Customer.cs and CustomerModel.cs and add two classes Customer,CustomerModel

public class Customer {  
    public int CustomerId { get; set; }  
    public string CompanyName { get; set; }  
    public string FirstName { get; set; }  
    public string MiddleName { get; set; }  
    public string LastName { get; set; }  
    public string Address { get; set; }  
    public string Phone { get; set; }  
    public string Country { get; set; }  
    public string City { get; set; }  
    public string Pincode { get; set; }  

public class CustomerModel {  
    public int CustomerId { get; set; }  
    public string FullName { get; set; }  
    public string Phone { get; set; }  
    public string Country { get; set; }  
    public string City { get; set; }  
    public string Pincode { get; set; }  
}  

Step 3-

Create Mapping profile as CustomerProfile.cs

public class CustomerProfile : Profile {  
    public CustomerProfile () {  
        // Mapping properties from Customer to CustomerModel  
        CreateMap<Customer, CustomerModel> ()  
            .ForMember (dest =>  
                dest.FullName,  
                opt => opt.MapFrom (src => src.FirstName + " " + src.MiddleName + " " + src.LastName));  
        // ForMember is used incase if any field doesn't match  
    }  
}  

Step 4-

To invoke mapped object in code

public class HomeController : Controller {  
    private readonly IMapper _mapper;  
    public HomeController (IMapper mapper) {  
        _mapper = mapper;  
    }  
    public IActionResult Index () {  
        Customer customerdetails = new Customer () {  
            CustomerId = 1,  
            CompanyName = "ABC",  
            Address = "Banaglore",  
            Phone = "000",  
            FirstName = "Shwetha",  
            MiddleName = "Amit",  
            LastName = "Naik",  
            City = "Bangalore",  
            Country = "India",  
            Pincode = "560091"  
        };  
        var customerModel = _mapper.Map<CustomerModel> (customerdetails);  
        var fullname = customerModel.FullName;  
        var address = customerModel.City;  
        return View ();  
    }  
}  

No comments:

Post a Comment