Nuget
Install-Package AutoMapper -Version 4.2.1
namespace :
using AutoMapper;
Must register dual ways.
Mapper.CreateMap<StudentBo, StudentViewModel>(); Mapper.CreateMap<StudentViewModel, StudentBo>();
Bean Class
From
public class Customer {
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
To
public class CustomerModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Unique { get; set; }
}
Simple Object Mapping
public JsonResult SaveCustomer() {
Customer c = new Customer
{
Name = "Chamith",
Address = "Ganemulla"
};
// create map
Mapper.CreateMap<Customer, CustomerModel>();
// create object
CustomerModel cc = Mapper.Map<CustomerModel>(c);
return Json(cc,JsonRequestBehavior.AllowGet);
}
List Mapping
public JsonResult SaveCustomer2()
{
List<Customer> c = new List<Customer>
{
new Customer {
Name = "Chamith",
Address = "Ganemulla" },
new Customer {
Name = "Kasun",
Address = "Singa" },
new Customer {
Name = "Sajee",
Address = "Kandana" }
};
// Normal way
List<CustomerModel> cc = c.Select(x => new CustomerModel
{
Address = x.Address,
Id = x.Id,
Name = x.Name
}).ToList();
//Automapper way
//Create a map
Mapper.CreateMap<Customer, CustomerModel>();
//create destination object using map
List<CustomerModel> cc2 = c.Select(x => AutoMapper.Mapper.Map<CustomerModel>(x)).ToList();
return Json(cc2, JsonRequestBehavior.AllowGet);
}
Map with Extra attributes
public JsonResult SaveCustomer() {
Customer c = new Customer
{
Name = "Chamith",
Address = "Ganemulla"
};
// create map with extra attribute
Mapper.CreateMap<Customer, CustomerModel>()
.ForMember(des => des.Unique, p2 => p2.MapFrom(sou => $"{sou.Id}_{sou.Name}"));
// create object
CustomerModel cc = Mapper.Map<CustomerModel>(c);
return Json(cc,JsonRequestBehavior.AllowGet);
}
}
Map List with Extra Items
Mapper.CreateMap<ApprovalsData, FacilityApprovalsDataViewModel>()
.ForMember(des => des.StatusInfo, p2 => p2.MapFrom(sou => $"{((sou.IsApproved)?1:0)}%{(sou.IsRejected?1:0)}"));
var data = response.ApprovalsData.Select(x => AutoMapper.Mapper.Map<FacilityApprovalsDataViewModel>(x)).ToList();
No comments:
Post a Comment