ModelConstructor.cs 7.31 KB
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace Quiz.Utility
{
    /// <summary>
    /// 数据模型构造器。
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public static class ModelConstructor<T> where T : class, new()
    {
        /// <summary>
        /// 根据datarow中数据,创建一个属性与其列名相对应的数据模型。
        /// </summary>
        /// <param name="datarow"></param>
        /// <returns></returns>
        public static T CreateModel(System.Data.DataRow datarow)
        {
            return ModelConstructor.CreateModel(typeof(T), datarow) as T;
        }
        /// <summary>
        /// 根据datarowview中数据,创建一个属性与其列名相对应的数据模型。
        /// </summary>
        /// <param name="datarowview"></param>
        /// <returns></returns>
        public static T CreateModel(System.Data.DataRowView datarowview)
        {
            return ModelConstructor.CreateModel(typeof(T), datarowview) as T;
        }
        /// <summary>
        /// 根据datareader中当前读取行数据,创建一个属性与其列名相对应的数据模型。
        /// </summary>
        /// <param name="datareader"></param>
        /// <returns></returns>
        public static T CreateModel(System.Data.SqlClient.SqlDataReader datareader)
        {
            return ModelConstructor.CreateModel(typeof(T), datareader) as T;
        }
        /// <summary>
        /// 根据datatable中数据,创建一个属性与其列名相对应的数据模型集合。
        /// </summary>
        /// <param name="datatable"></param>
        /// <returns></returns>
        public static T[] CreateModels(System.Data.DataTable datatable)
        {
            if (datatable == null || datatable.Rows.Count <= 0) return new T[0];
            List<T> list = new List<T>();
            for (int i = 0; i < datatable.Rows.Count; i++) list.Add(CreateModel(datatable.Rows[i]));
            return list.ToArray();
        }
        /// <summary>
        /// 根据datatable中数据,创建一个属性与其列名相对应的数据模型集合。
        /// </summary>
        /// <param name="datatable"></param>
        /// <returns></returns>
        public static List<T> CreateModelList(System.Data.DataTable datatable)
        {
            if (datatable == null || datatable.Rows.Count <= 0) return new List<T>();
            List<T> list = new List<T>();
            for (int i = 0; i < datatable.Rows.Count; i++) list.Add(CreateModel(datatable.Rows[i]));
            return list;
        }

        /// <summary>
        /// 根据xml中数据,创建一个属性与其列名相对应的数据模型集合。
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="createRoot"></param>
        /// <returns></returns>
        public static List<T> CreateModelList(string xml, bool createRoot = true)
        {
            try
            {
                if (createRoot) xml = string.Format("<root>{0}</root>", xml);
                XmlDocument document = new XmlDocument();
                document.LoadXml(xml);
                DataTable dt = new DataTable();
                var rootnode = document.SelectSingleNode("root");
                var first = rootnode.ChildNodes[0];
                foreach (XmlNode childNode in first.ChildNodes)
                {
                    dt.Columns.Add(childNode.Name);
                }
                foreach (XmlNode childNode in rootnode.ChildNodes)
                {
                    DataRow row = dt.NewRow();
                    foreach (XmlNode node in childNode.ChildNodes)
                    {
                        row[node.Name] = node.InnerText;
                    }
                    dt.Rows.Add(row);
                }
                return CreateModelList(dt);
            }
            catch
            {
                return new List<T>();
            }
        }
    }
    /// <summary>
    /// 数据模型构造器。
    /// </summary>
    static class ModelConstructor
    {
        internal static object CreateModel(Type modelType, System.Data.DataRow datarow)
        {
            object model = modelType.Assembly.CreateInstance(modelType.ToString());
            System.Reflection.PropertyInfo[] pinfolist = modelType.GetProperties();
            if (pinfolist == null || pinfolist.Length <= 0) return model;
            for (int i = 0; i < pinfolist.Length; i++)
            {
                if (!datarow.Table.Columns.Contains(pinfolist[i].Name)) continue;
                object value = datarow[pinfolist[i].Name];
                if (value is DBNull || value == null) continue;
                Type changeType = pinfolist[i].PropertyType;
                if (changeType.ToString() == "System.Guid") value = new Guid(value.ToString());
                else if (changeType.IsGenericType && changeType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) changeType = Nullable.GetUnderlyingType(changeType);
                pinfolist[i].SetValue(model, Convert.ChangeType(value, changeType), null);

            }
            return model;
        }

        internal static object CreateModel(Type modelType, System.Data.DataRowView datarowview)
        {
            object model = modelType.Assembly.CreateInstance(modelType.ToString());
            System.Reflection.PropertyInfo[] pinfolist = modelType.GetProperties();
            if (pinfolist == null || pinfolist.Length <= 0) return model;
            for (int i = 0; i < pinfolist.Length; i++)
            {
                if (!datarowview.DataView.Table.Columns.Contains(pinfolist[i].Name)) continue;
                object value = datarowview[pinfolist[i].Name];
                if (value is DBNull || value == null) continue;
                Type changeType = pinfolist[i].PropertyType;
                if (changeType.ToString() == "System.Guid") value = new Guid(value.ToString());
                else if (changeType.IsGenericType && changeType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) changeType = Nullable.GetUnderlyingType(changeType);
                pinfolist[i].SetValue(model, Convert.ChangeType(value, changeType), null);
            }
            return model;
        }

        internal static object CreateModel(Type modelType, System.Data.SqlClient.SqlDataReader datareader)
        {
            object model = modelType.Assembly.CreateInstance(modelType.ToString());
            System.Reflection.PropertyInfo[] pinfolist = modelType.GetProperties();
            if (pinfolist == null || pinfolist.Length <= 0) return model;
            for (int i = 0; i < pinfolist.Length; i++)
            {
                if (datareader.GetOrdinal(pinfolist[i].Name) < 0) continue;
                object value = datareader[pinfolist[i].Name];
                if (value is DBNull || value == null) continue;
                Type changeType = pinfolist[i].PropertyType;
                if (changeType.ToString() == "System.Guid") value = new Guid(value.ToString());
                else if (changeType.IsGenericType && changeType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) changeType = Nullable.GetUnderlyingType(changeType);
                pinfolist[i].SetValue(model, Convert.ChangeType(value, changeType), null);
            }
            return model;
        }
    }
}