What is AutoMapper?
Simply put, it's code that maps one object to another. Get rid of the cumbersome assignment process (the most common is Model --- ViewModel)
AutoMapper installation
I am using VS2015 and can directly enter AutoMapper in NuGet to download
You can also use console commands
PM> Install-Package AutoMapper
Here I define two classes ShopingInfo ShopingInfoViewModel
public class ShopingInfo:EntityBase { public string ShopingName { get; set; } public int ShopingCount { get; set; } public decimal ShopingPric { get; set; } public int Stock { get; set; } public int Volumeofvolume { get; set; } public int ShopingTypeId { get; set; } public virtual ShopingType ShopingType { get; set; } }
public class ShopingInfoViewModel { public int ID { get; set; } public string ShopingName { get; set; } public int ShopingCount { get; set; } public decimal ShopingPric { get; set; } public int Stock { get; set; } public int Volumeofvolume { get; set; } public string ShopingTypeName { get; set; } }
namespace to be used
using AutoMapper;
Then a special class was built to store these mappings SourceProfile and inherited Profile
public class SourceProfile : Profile { public SourceProfile() { base.CreateMap<ShopingInfo, ShopingInfoViewModel>(); } }
If we find that there are inconsistent field names in the two categories.
For example, I changed the ShopingName in the shopingInfoViewModel to Name, then you can write like this
public class SourceProfile : Profile { public SourceProfile() { base.CreateMap<ShopingInfo, ShopingInfoViewModel>(); // base.CreateMap<ShopingInfo, ShopingInfoViewModel>().ForMember(x => x.Name, // q => { q.MapFrom(z => z.ShopingName); // }); } }
Created an intermediate class to encapsulate the above code
public class AutoMapper { public static void Start() { Mapper.Initialize(x => { x.AddProfile<SourceProfile>(); }); } }
Then in the global class Global, make the startup initialization load and add the following code
AutoMapper.Start();
Okay. The basics are all done. Now test it and
you can see that it has been mapped.
Learning cannot stop. Learn something every day. make yourself more valuable