2014年8月5日 星期二

AutoMapper 簡單用法

AutoMapper是一個用來處理類別之間轉換的套件,以下用個Model和ViewModel的轉換當例子

首先是一個簡單的Model
public class DemoModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

再來是對應的ViewModel
public class DemoViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

兩個類別要轉換的一般寫法
private static void V1()
{
    DemoModel c1 = new DemoModel()
    {
        Id = 123,
        Name = "abc"
    };

    DemoViewModel c2 = new DemoViewModel
    {
        Id = c1.Id,
        Name = c1.Name
    };

    Console.WriteLine("id:{0}, name:{1}", c2.Id, c2.Name);
}

使用AutoMapper之後的寫法
private static void V2()
{
    Mapper.CreateMap<DemoModel, DemoViewModel>();
    DemoModel c1 = new DemoModel
    {
        Id = 123,
        Name = "abc"
    };

    DemoViewModel c2 = Mapper.Map<DemoModel, DemoViewModel>(c1);
    Console.WriteLine("id:{0}, name:{1}", c2.Id, c2.Name);
}

AutoMapper用來把DataReader轉成IEnumerable也很簡單,以北風資料庫的Customers為例子
首先是轉換後的CustViewModel
public class CustViewModel
{
    public int CustomerID { get; set; }
    public string CompanyName { get; set; }
    public string City { get; set; }
    public string Region { get; set; }
    public string PostalCode { get; set; }
    public string Country { get; set; }
    public string Phone { get; set; }
    public string Fax { get; set; }
}

取得資料列表
public static IEnumerable<CustViewModel> GetList()
{
    Mapper.CreateMap<IDataReader, IEnumerable<CustViewModel>>();
    string connString = @"data source=(localdb)\v11.0; initial catalog=Northwind; trusted_connection=true;";
    using (SqlConnection conn = new SqlConnection(connString))
    {
        SqlCommand cmd = new SqlCommand("select * from customers", conn);
        conn.Open();
        SqlDataReader dtr = cmd.ExecuteReader();
        return Mapper.Map<IDataReader, IEnumerable<CustViewModel>>(dtr);
    }
}