欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C# DataTable 轉(zhuǎn)換為 實(shí)體類對(duì)象實(shí)例

 更新時(shí)間:2013年04月18日 10:44:01   作者:  
如果你的實(shí)體類與數(shù)據(jù)庫(kù)表是完全一致的。上代碼:

復(fù)制代碼 代碼如下:

public class User
{
        public int ID { get; set; }
        public string Name { get; set; }
}

//對(duì)應(yīng)數(shù)據(jù)庫(kù)表:
//User
//字段:ID、Name    

那么你也許需要編寫將DataTable 轉(zhuǎn)換為實(shí)體對(duì)象的方法,便利DataTable.Rows 獲得并填充。。

下面是我寫的一個(gè)通用方法,分享+記錄,便于日后直接Copy ~

復(fù)制代碼 代碼如下:

private static List<T> TableToEntity<T>(DataTable dt) where T : class,new()
{
    Type type = typeof(T);
    List<T> list = new List<T>();

    foreach (DataRow row in dt.Rows)
    {
        PropertyInfo[] pArray = type.GetProperties();
        T entity = new T();
        foreach (PropertyInfo p in pArray)
        {
            if (row[p.Name] is Int64)
            {
                p.SetValue(entity, Convert.ToInt32(row[p.Name]), null);
                continue;
            }
            p.SetValue(entity, row[p.Name], null);
        }
        list.Add(entity);
    }
    return list;
}
  

// 調(diào)用:

List<User> userList = TableToEntity<User>(YourDataTable);

相關(guān)文章

最新評(píng)論