AutoMapper

在寫ASP.NET MVC時,經常需要在ViewModel與Model之間做轉換。此時可以使用AutoMapper套件來簡化程式,讓程式變得更優雅。

詳細說明可以參考:https://github.com/AutoMapper/AutoMapper/wiki

 # Customer.cs
  public class Customer
  {
      public string Company { get; set; }
      public string FirstName { get; set; }
      public string LastName { get; set; }
  }
 # CustomerViewModel.cs
  public class CustomerViewModel
  {
      public string Company { get; set; }
      public string FirstName { get; set; }
      public string FullName { get; set; }
      public string LastName { get; set; }
  }
# Mapper.cs
Mapper.Initialize(
   cfg => cfg.CreateMap<Customer, CustomerViewModel>()
    .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => string.Format("{0} {1}",   
    src.LastName, src.FirstName)))
);

Customer v1 = new Customer
{
  FirstName = "Allen",
  LastName = "Huang"
};

CustomerViewModel c1 = Mapper.Map<Customer, CustomerViewModel>(v1);

results matching ""

    No results matching ""