zoukankan      html  css  js  c++  java
  • DataTable转List<Model>通用类【实体转换辅助类】

    /// <summary>

    /// DataTable转List<Model>通用类【实体转换辅助类】

    /// </summary>

    public class ModelConvertHelper<T> where T : new()

    {

    public static IList<T> ConvertToModel(DataTable dt)

    {

    // 定义集合

    IList<T> ts = new List<T>();

    // 获得此模型的类型

    Type type = typeof(T);

    string tempName = "";

    foreach (DataRow dr in dt.Rows)

    {

    T t = new T();

    // 获得此模型的公共属性

    PropertyInfo[] propertys = t.GetType().GetProperties();

    foreach (PropertyInfo pi in propertys)

    {

    tempName = pi.Name; // 检查DataTable是否包含此列

    if (dt.Columns.Contains(tempName))

    {

    // 判断此属性是否有Set

    if (!pi.CanWrite) continue;

    object value = dr[tempName];

    if (value != DBNull.Value)

    pi.SetValue(t, value, null);

    }

    }

    ts.Add(t);

    }

    return ts;

    }

    }


    //方法二:使用emit实现
    public static List<TResult> ToList<TResult>(this DataTable dt) where TResult : class, new()

    {

                List<TResult> list = new List<TResult>();

                if (dt == null) return list;

                DataTableEntityBuilder<TResult> eblist = DataTableEntityBuilder<TResult>.CreateBuilder(dt.Rows[0]);

                foreach(DataRow info in dt.Rows) list.Add(eblist.Build(info));

                dt.Dispose(); dt = null;

                return list;

    }

    public class DataTableEntityBuilder<Entity>

    {

            private static readonly MethodInfo getValueMethod = typeof(DataRow).GetMethod("get_Item", new Type[] { typeof(int) });

            private static readonly MethodInfo isDBNullMethod = typeof(DataRow).GetMethod("IsNull", new Type[] { typeof(int) });

            private delegate Entity Load(DataRow dataRecord);

            private Load handler;

            private DataTableEntityBuilder() { }

            public Entity Build(DataRow dataRecord) {

                return handler(dataRecord);

            }

            public static DataTableEntityBuilder<Entity> CreateBuilder(DataRow dataRecord) {

                DataTableEntityBuilder<Entity> dynamicBuilder = new DataTableEntityBuilder<Entity>();

                DynamicMethod method = new DynamicMethod("DynamicCreateEntity", typeof(Entity), new Type[] { typeof(DataRow) }, typeof(Entity), true);

                ILGenerator generator = method.GetILGenerator();

                LocalBuilder result = generator.DeclareLocal(typeof(Entity));

                generator.Emit(OpCodes.Newobj, typeof(Entity).GetConstructor(Type.EmptyTypes));

                generator.Emit(OpCodes.Stloc, result);

                for (int i = 0; i < dataRecord.ItemArray.Length; i++) {

                    PropertyInfo propertyInfo = typeof(Entity).GetProperty(dataRecord.Table.Columns[i].ColumnName);

                    Label endIfLabel = generator.DefineLabel();

                    if (propertyInfo != null && propertyInfo.GetSetMethod() != null) {

                        generator.Emit(OpCodes.Ldarg_0);

                        generator.Emit(OpCodes.Ldc_I4, i);

                        generator.Emit(OpCodes.Callvirt, isDBNullMethod);

                        generator.Emit(OpCodes.Brtrue, endIfLabel);

                        generator.Emit(OpCodes.Ldloc, result);

                        generator.Emit(OpCodes.Ldarg_0);

                        generator.Emit(OpCodes.Ldc_I4, i);

                        generator.Emit(OpCodes.Callvirt, getValueMethod);

                        generator.Emit(OpCodes.Unbox_Any, propertyInfo.PropertyType);

                        generator.Emit(OpCodes.Callvirt, propertyInfo.GetSetMethod());

                        generator.MarkLabel(endIfLabel);

                    }

                }

                generator.Emit(OpCodes.Ldloc, result);

                generator.Emit(OpCodes.Ret);

                dynamicBuilder.handler = (Load)method.CreateDelegate(typeof(Load));

                return dynamicBuilder;

            }

        }

    佛为心,道为骨,儒为表,大度看世界; 技在手,能在身,思在脑,从容过生活; 三千年读史,不外功名利禄; 九万里悟道,终归诗酒田园;
  • 相关阅读:
    printf里的=、++
    线程也疯狂-----异步编程
    自己搭建node服务器环境(请求静态资源、get请求、post请求)
    React学习
    2020.10-2021-01总结
    接圈的作用和缺点
    CWnd,HWND; CDC,HDC
    Python通过requests模块处理form-data请求格式
    element-ui resetFields 无效的问题
    用python 将数字每三组分割
  • 原文地址:https://www.cnblogs.com/taofx/p/4137660.html
Copyright © 2011-2022 走看看