天天看點

DataTable轉換為List<Model>的通用類

在開發中,把查詢結果以datatable傳回很友善,但是在檢索資料時又很麻煩,沒有模型類型檢索友善。

是以很多人都是按照以下方式做的:

// 獲得查詢結果

datatable dt =

dbhelper.executedatatable(...);

//

把datatable轉換為ilist<userinfo>

ilist<userinfo> users =

converttouserinfo(dt);

問題:如果此系統有幾十上百個模型,那不是每個模型中都要寫個把datatable轉換為此模型的方法嗎?

解決:能不能寫個通用類,可以把datatable轉換為任何模型,呵呵,這就需要利用反射和泛型了

不多說,核心代碼如下,經過測試,性能不錯,大家可以根據實際情況改善

using system;

using system.collections.generic;

using system.text;

using system.data;

using system.reflection;

namespace ncl.data

{

    /// <summary>

    /// 實體轉換輔助類

    /// </summary>

    public class modelconverthelper<t> where  t : new()

    {

        public static ilist<t> converttomodel(datatable dt)

        {

            // 定義集合

            ilist<t> ts = new list<t>();

            // 獲得此模型的類型

            type type = typeof(t);

            string tempname = "";

            foreach (datarow dr in dt.rows)

            {

                t t = new t();

                // 獲得此模型的公共屬性

                propertyinfo[] propertys = t.gettype().getproperties();

                foreach (propertyinfo pi in propertys)

                {

                    tempname = pi.name;

                    // 檢查datatable是否包含此列

                    if (dt.columns.contains(tempname))

                    {

                        // 判斷此屬性是否有setter

                        if (!pi.canwrite) continue;

                        object value = dr[tempname];

                        if (value != dbnull.value)

                            pi.setvalue(t, value, null);

                    }

                }

                ts.add(t);

            }

            return ts;

        }

    }

}

使用方式:

modelconverthelper<userinfo>.converttomodel(dt);

呵呵,這樣子是不是很友善了,謝謝,希望能給你帶來收獲!