AutoMapper的一些簡(jiǎn)單應(yīng)用和擴(kuò)展

最近在項(xiàng)目中用到了AutoMapper,在我項(xiàng)目中只用到了AutoMapper的一些簡(jiǎn)單功能。如對(duì)象轉(zhuǎn)換、將sql查詢出來的Datatable轉(zhuǎn)換為實(shí)體集合。將實(shí)體集合轉(zhuǎn)換為Datatable,我看了半天,好像AutoMapper不支持...,于是就自己實(shí)現(xiàn)了一個(gè)功能。
下面是我將用到的部分功能做了擴(kuò)展,主要還是用的擴(kuò)展方法,方便調(diào)用。
<pre>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoMapper;
using System.Collections;
using System.Data;
using System.Reflection;

namespace LY.AutoMapper
{
public static class AutoMapperExtension
{
/// <summary>
/// 實(shí)體對(duì)象轉(zhuǎn)換
/// </summary>
/// <typeparam name="TDestination"></typeparam>
/// <param name="o"></param>
/// <returns></returns>
public static TDestination MapTo<TDestination>(this object o)
{
if (o == null)
throw new ArgumentNullException();

        Mapper.CreateMap(o.GetType(), typeof(TDestination));

        return Mapper.Map<TDestination>(o); ;
    }


    /// <summary>
    /// 集合轉(zhuǎn)換
    /// </summary>
    /// <typeparam name="TDestination"></typeparam>
    /// <param name="o"></param>
    /// <returns></returns>
    public static List<TDestination> MapTo<TDestination>(this IEnumerable o)
    {
        if (o == null)
            throw new ArgumentNullException();


        foreach (var item in o)
        {
            Mapper.CreateMap(item.GetType(), typeof(TDestination));

            break;
        }
        return Mapper.Map<List<TDestination>>(o);
    }


    /// <summary>  
    /// 將 DataTable 轉(zhuǎn)為實(shí)體對(duì)象  
    /// </summary>  
    /// <typeparam name="T"></typeparam>  
    /// <param name="dt"></param>  
    /// <returns></returns>  
    public static List<T> MapTo<T>(this DataTable dt)
    {
        if (dt == null || dt.Rows.Count == 0)
            return default(List<T>);

        Mapper.CreateMap<IDataReader, T>();
        return Mapper.Map<List<T>>(dt.CreateDataReader());
    }


    /// <summary>
    /// 將List轉(zhuǎn)換為Datatable
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list"></param>
    /// <returns></returns>
    public static DataTable MapToTable<T>(this IEnumerable list)
    {
        if (list == null)
            return default(DataTable);

        //創(chuàng)建屬性的集合
        List<PropertyInfo> pList = new List<PropertyInfo>();
        //獲得反射的入口
        Type type = typeof(T);
        DataTable dt = new DataTable();
        //把所有的public屬性加入到集合 并添加DataTable的列
        Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
        foreach (var item in list)
        {
            //創(chuàng)建一個(gè)DataRow實(shí)例
            DataRow row = dt.NewRow();
            //給row 賦值
            pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
            //加入到DataTable
            dt.Rows.Add(row);
        }
        return dt;
    }

}

}
</pre>
將List轉(zhuǎn)換為DataTable,因?yàn)槲覜]看到AutoMapper支持(或許研究的不深...),所以這里用了反射的實(shí)現(xiàn)。這樣的話,這個(gè)擴(kuò)展類就支持從Datatable to List,List to Datatable了。

下面我們進(jìn)行測(cè)試。
新建兩個(gè)類,模擬Entity與Model。
<pre>
namespace LY.AutoMapper.Test
{
public class StudentEntity
{
public string Name { get; set; }

    public int Age { get; set; }
}

}
</pre>
<pre>
namespace LY.AutoMapper.Test
{
public class StudentModel
{

    public string Name { get; set; }

    public int Age { get; set; }
}

}
</pre>
下面,是使用方法。
<pre>
private void btnTest_Click(object sender, EventArgs e)
{
StudentEntity stuEntity = new StudentEntity() { Name = "ly", Age = 29 };

        //實(shí)體轉(zhuǎn)換
        StudentModel stuModel = stuEntity.MapTo<StudentModel>();

        //集合轉(zhuǎn)換
        List<StudentEntity> strEntityList = new List<StudentEntity>()
          {
              new StudentEntity(){Name="aa",Age=15}
          };

        List<StudentModel> stuModelList = strEntityList.MapTo<StudentModel>();

        #region Get DataTable
        DataTable tb = new DataTable();
        tb.Columns.Add("Name");
        tb.Columns.Add("Age", typeof(Int32));

        DataRow row1 = tb.NewRow();
        row1[0] = "ly";
        row1[1] = 27;

        DataRow row2 = tb.NewRow();
        row2[0] = "yy";
        row2[1] = 26;

        tb.Rows.Add(row1);
        tb.Rows.Add(row2);
        #endregion

        //Datatable轉(zhuǎn)換為L(zhǎng)ist
        List<StudentEntity> stuEntitys = tb.MapTo<StudentEntity>();

        //List轉(zhuǎn)換為Datatable
        DataTable tbTest = stuEntitys.MapToTable<StudentEntity>();
 
    }

</pre>

當(dāng)然,如果項(xiàng)目中使用了EF,利用AutoMapper可以很方便的將數(shù)據(jù)持久層轉(zhuǎn)換為我們定義的Model,節(jié)省了很多代碼量。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,346評(píng)論 25 708
  • WebSocket-Swift Starscream的使用 WebSocket 是 HTML5 一種新的協(xié)議。它實(shí)...
    香橙柚子閱讀 24,829評(píng)論 8 183
  • 故事太早 年輕的心 還不能一一整理開場(chǎng)的序言 順流而來的風(fēng) 拂過臉頰 這一瞬 是給 故事的開場(chǎng) 是給過往 云煙里自...
    凡夢(mèng)之愿閱讀 216評(píng)論 0 0
  • 老陳開車進(jìn)來時(shí)大約是下午6點(diǎn)多一點(diǎn),想著索性沒網(wǎng)沒電,距離天黑又還有三個(gè)小時(shí),不如一口氣游完新措,說不定第二天趕早...
    小知了a閱讀 1,166評(píng)論 0 3
  • 凌晨昏昏不能眠,作詩(shī)一首。晨起甚早,食湯麵及雞子。上午處理雜務(wù),然後坐地鐵、高鐵至珠海,又於橫琴島上處理技術(shù)工作,...
    寒窗寄傲生閱讀 199評(píng)論 0 0

友情鏈接更多精彩內(nèi)容