Home > Backend Development > C#.Net Tutorial > C# DataTable converted to entity class object instance

C# DataTable converted to entity class object instance

高洛峰
Release: 2017-01-18 09:34:47
Original
2244 people have browsed it

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

//对应数据库表: 
//User 
//字段:ID、Name
Copy after login

Then you may need to write a method to convert the DataTable into an entity object to facilitate DataTable.Rows to obtain and fill it. .

The following is a general method I wrote, share + record, easy to copy directly in the future ~

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; 
} 
  
// 调用:
List<User> userList = TableToEntity<User>(YourDataTable);
Copy after login

For more articles related to converting C# DataTable into entity class object instances, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template