|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoMapper;
namespace AutoMapperDemo
{
class Program
{
static void Main(string[] args)
{
var program = new Program();
Mapper.CreateMap<Customer, CustomerViewItem>()
.ForMember(cv => cv.FullName, m => m.MapFrom(s => s.FirstName + " " + s.LastName))
.ForMember(cv => cv.VIP, m => m.ResolveUsing<VIPResolver>().FromMember(x => x.VIP))
.ForMember(cv => cv.DateOfBirth, m => m.AddFormatter<DateFormatter>());
program.Run();
}
private void Run()
{
Customer customer = GetCustomerFromDB();
CustomerViewItem customerViewItem = Mapper.Map<Customer, CustomerViewItem>(customer);
ShowCustomerInDataGrid(customerViewItem);
}
private void ShowCustomerInDataGrid(CustomerViewItem customerViewItem) { }
private Customer GetCustomerFromDB()
{
return new Customer()
{
DateOfBirth = new DateTime(1987, 11, 2),
FirstName = "Andriy",
LastName = "Buday",
NumberOfOrders = 7,
Company = new Company() { Name = "andriybuday.blogspot.com" },
VIP = true
};
}
}
public class Customer
{
public Company Company { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public int NumberOfOrders { get; set; }
public bool VIP { get; set; }
}
public class Company
{
public string Name { get; set; }
}
public class CustomerViewItem
{
public string CompanyName { get; set; }
public string FullName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
//public DateTime DateOfBirth { get; set; }
public string DateOfBirth { get; set; }
public int NumberOfOrders { get; set; }
public string VIP { get; set; }
}
public class VIPResolver : ValueResolver<bool, string>
{
protected override string ResolveCore(bool source)
{
return source ? "Y" : "N";
}
}
public class DateFormatter : IValueFormatter
{
public string FormatValue(ResolutionContext context)
{
return ((DateTime)context.SourceValue).ToLongDateString();
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
I'm very pragmatic and self-improving person. My goal is to become successful community developer.
I'm young and love learning, these are precondition to my success.
Currently I'm working in dedicated Ukrainian outsourcing company SoftServe as .NET developer on enterprise project. In everyday work I'm interacting with lot of technologies which are close to .NET (NHibernate, UnitTesting, StructureMap, WCF, Win/WebServices, and so on...)
Feel free to contact me.