DataTable转List<T>,从数据库对象转实体对象的自动实现

来源:互联网 发布:美工详情页一般多少钱 编辑:程序博客网 时间:2024/06/07 17:52

在这里我所说的从数据库对象转实体对象的自动实现,指的是DataTable自动转换好List<T>。

要实现这个功能,基于以下两点:

1:DataTable中列的名称和实体对象Entity中属性的名称同名(不区分大小写)。

2:当DataTable中的数值不能正确转换时(如为空的时候转为int)可指定Entity的默认值来避免错误发生。

主要用到了反射机制和特性。

代码如下

using System;using System.Collections.Generic;using System.Data;using System.Linq;using System.Reflection;using System.Text;namespace 数据层{    public class DataTableToListT    {        public static List<T> ToList<T>(DataTable dataTable)        {            List<T> list = null;            if (dataTable != null && dataTable.Rows.Count > 0)            {                list = new List<T>();                Type t = typeof(T);                PropertyInfo[] pinfo = t.GetProperties();                for (int i = 0; i < dataTable.Rows.Count; i++)                {                    T item;                    object objInstance = Activator.CreateInstance(t, true);                    for (int j = 0; j < dataTable.Columns.Count; j++)                    {                        string colName = dataTable.Columns[j].ColumnName;                        for (int k = 0; k < pinfo.Length; k++)                        {                            if (colName.Equals(pinfo[k].Name, StringComparison.OrdinalIgnoreCase))                            {                                object defaultvalue = null;                                object[] proAttributes = pinfo[k].GetCustomAttributes(typeof(DataValueDefaultAttribute), false);                                if (proAttributes.Length > 0)                                {                                    DataValueDefaultAttribute loDefectTrack = (DataValueDefaultAttribute)proAttributes[0];                                    defaultvalue = loDefectTrack.Value;                                }                                pinfo[k].SetValue(objInstance, Map(pinfo[k].PropertyType.ToString(), dataTable.Rows[i][colName].ToString(), defaultvalue), null);                            }                        }                    }                    item = (T)objInstance;                    list.Add(item);                }            }            return list;        }        private static object Map(string enType, string dbValue, object defaultvalue)        {            switch (enType.ToLower().Split('.')[1])            {                case "boolean":                    try                    {                        return Convert.ToBoolean(dbValue);                    }                    catch                    {                        if (defaultvalue != null)                        {                            return Convert.ToBoolean(defaultvalue);                        }                        else { throw new Exception("参数转换错误且未指定默认值,请检查数据类型或使用DataValueDefaultAttribute特性指定默认值"); }                    }                case "sbyte":                    try                    {                        return Convert.ToSByte(dbValue);                    }                    catch                    {                        if (defaultvalue != null)                        {                            return Convert.ToSByte(defaultvalue);                        }                        else { throw new Exception("参数转换错误且未指定默认值,请检查数据类型或使用DataValueDefaultAttribute特性指定默认值"); }                    }                case "int16":                    try                    {                        return Convert.ToInt16(dbValue);                    }                    catch                    {                        if (defaultvalue != null)                        {                            return Convert.ToInt16(defaultvalue);                        }                        else { throw new Exception("参数转换错误且未指定默认值,请检查数据类型或使用DataValueDefaultAttribute特性指定默认值"); }                    }                case "int32":                    try                    {                        return Convert.ToInt32(dbValue);                    }                    catch                    {                        if (defaultvalue != null)                        {                            return Convert.ToInt32(defaultvalue);                        }                        else { throw new Exception("参数转换错误且未指定默认值,请检查数据类型或使用DataValueDefaultAttribute特性指定默认值"); }                    }                case "int64":                    try                    {                        return Convert.ToInt64(dbValue);                    }                    catch                    {                        if (defaultvalue != null)                        {                            return Convert.ToInt64(defaultvalue);                        }                        else { throw new Exception("参数转换错误且未指定默认值,请检查数据类型或使用DataValueDefaultAttribute特性指定默认值"); }                    }                case "uint16":                    try                    {                        return Convert.ToUInt16(dbValue);                    }                    catch                    {                        if (defaultvalue != null)                        {                            return Convert.ToUInt16(defaultvalue);                        }                        else { throw new Exception("参数转换错误且未指定默认值,请检查数据类型或使用DataValueDefaultAttribute特性指定默认值"); }                    }                case "uint32":                    try                    {                        return Convert.ToUInt32(dbValue);                    }                    catch                    {                        if (defaultvalue != null)                        {                            return Convert.ToUInt32(defaultvalue);                        }                        else { throw new Exception("参数转换错误且未指定默认值,请检查数据类型或使用DataValueDefaultAttribute特性指定默认值"); }                    }                case "uint64":                    try                    {                        return Convert.ToUInt64(dbValue);                    }                    catch                    {                        if (defaultvalue != null)                        {                            return Convert.ToUInt64(defaultvalue);                        }                        else { throw new Exception("参数转换错误且未指定默认值,请检查数据类型或使用DataValueDefaultAttribute特性指定默认值"); }                    }                case "char":                    try                    {                        return Convert.ToChar(dbValue);                    }                    catch                    {                        if (defaultvalue != null)                        {                            return Convert.ToChar(defaultvalue);                        }                        else { throw new Exception("参数转换错误且未指定默认值,请检查数据类型或使用DataValueDefaultAttribute特性指定默认值"); }                    }                case "string":                    try                    {                        return Convert.ToString(dbValue);                    }                    catch                    {                        if (defaultvalue != null)                        {                            return Convert.ToString(defaultvalue);                        }                        else { throw new Exception("参数转换错误且未指定默认值,请检查数据类型或使用DataValueDefaultAttribute特性指定默认值"); }                    }                case "byte":                    try                    {                        return Convert.ToByte(dbValue);                    }                    catch                    {                        if (defaultvalue != null)                        {                            return Convert.ToByte(defaultvalue);                        }                        else { throw new Exception("参数转换错误且未指定默认值,请检查数据类型或使用DataValueDefaultAttribute特性指定默认值"); }                    }                case "single":                    try                    {                        return Convert.ToSingle(dbValue);                    }                    catch                    {                        if (defaultvalue != null)                        {                            return Convert.ToSingle(defaultvalue);                        }                        else { throw new Exception("参数转换错误且未指定默认值,请检查数据类型或使用DataValueDefaultAttribute特性指定默认值"); }                    }                case "double":                    try                    {                        return Convert.ToDouble(dbValue);                    }                    catch                    {                        if (defaultvalue != null)                        {                            return Convert.ToDouble(defaultvalue);                        }                        else { throw new Exception("参数转换错误且未指定默认值,请检查数据类型或使用DataValueDefaultAttribute特性指定默认值"); }                    }                case "decimal":                    try                    {                        return Convert.ToDecimal(dbValue);                    }                    catch                    {                        if (defaultvalue != null)                        {                            return Convert.ToDecimal(defaultvalue);                        }                        else { throw new Exception("参数转换错误且未指定默认值,请检查数据类型或使用DataValueDefaultAttribute特性指定默认值"); }                    }                case "datetime":                    try                    {                        return Convert.ToDateTime(dbValue);                    }                    catch                    {                        if (defaultvalue != null)                        {                            return Convert.ToDateTime(defaultvalue);                        }                        else { throw new Exception("参数转换错误且未指定默认值,请检查数据类型或使用DataValueDefaultAttribute特性指定默认值"); }                    }                default:                    return Convert.ToString(dbValue);            }        }    }    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]    public class DataValueDefaultAttribute : Attribute    {        private object value;        public DataValueDefaultAttribute(object value)        {            this.value = value;        }        public object Value { get { return value; } }    }}

using System;using System.Collections.Generic;using System.Data.Common;using System.Linq;using System.Reflection;using System.Text;using System.Data;namespace 数据层{    class Program    {        static void Main(string[] args)        {                   DataTable dt = new DataTable();                    dt.Columns.Add("ID");            dt.Rows.Add("");//演示转换错误的情况            dt.Rows.Add("2");            List<EntityA> list2 = DataTableToListT.ToList<EntityA>(dt);            foreach (var item in list2)            {                Console.WriteLine(item.ID);            }            Console.ReadKey();        }    }    public class EntityA    {        [DataValueDefaultAttribute(1)]  //指定默认值        public int ID { get; set; }      }}


0 0