AutoMapper

  • 62
  • 0

AutoMapper

 

old method

public ActionResult sample()
{
   var objResult=db.Customer();
   
   List<Customer> customers = new List <Customer>();

   foreach (var item in objResult)
   {
     customers.Add(new Customer()
     {
       CustomerID = item.CustomerID,
       CompanyName = item.CompanyName,
       ContactName = item.ContactaNmae,
       ContactTitle = item.ContactTitle,
       Address = item.Address,
       City = item.City,
       Region = item.Region,
       PostalCode= item.PostalCode,
       Country = item.Country,
       Phone = item.Phone,
       Fax = item.Fax
     });
   }
   
   return View(customers);
}

 

 

new method

1.downLoad AutoMapper

2.

public ActionResult sample()
{
  var objResult = db.Customer();
  
  Mapper.CreateMap<objResult,Customer>();
  
  List<Customer> customers = Mapper.Map<List<Customer>>(ObjResult.ToList());

   return View(customers); 

}

 

 

 

參考網址:mrkt