【转】C#中将DataTable数据转为实体对象
本文来自:http://blog.csdn.net/justseven/article/details/2917086
一个简单的将DataTable中的一行数据转为相应的实体对象
前提是 实体对象的属性名与DataTable中的列名一样。
- public class DataSet2Entity
- {
- public static T ConvertToEntity<T>(DataTable dt, DataRow row) where T : new()
- {
- System.Data.DataColumnCollection columns = dt.Columns;
- int iColumnCount = columns.Count;
- int i;
- int j;
- T t = new T();
- Type elementType;
- elementType = t.GetType();
- System.Reflection.PropertyInfo[] publicProperties = elementType.GetProperties();
- //if (!(publicProperties.Length > iColumnCount))
- //{
- for (i = 0; i < iColumnCount; i++)
- {
- for (j = 0; j < publicProperties.Length; j++)
- {
- if (columns[i].ColumnName.ToLower() == publicProperties[j].Name.ToLower())
- {
- if (publicProperties[j].PropertyType == typeof(int))
- {
- int num = 0;
- try
- {
- num = Convert.ToInt32(row[i]);
- }
- catch
- {
- }
- publicProperties[j].SetValue(t, num, null);
- }
- else
- if (publicProperties[j].PropertyType == typeof(string) && row[i] == System.DBNull.Value)
- {
- publicProperties[j].SetValue(t, "", null);
- }
- else
- {
- object value = row[i] == System.DBNull.Value ? null : row[i];
- publicProperties[j].SetValue(t, value, null);
- }
- }
- }
- }
- return t;
- }
- }