Esempio n. 1
0
        /// <summary>
        /// table转成其他类型datatable
        /// 20140326
        /// add by shwang
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="table">datatable</param>
        /// <returns>list/></returns>
        public static List <T> ConvertToList <T>(this DataTable table) where T : new()
        {
            if (table == null)
            {
                return(null);
            }

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

            if (table.Rows.Count == 0)
            {
                return(list);
            }

            DataTableEntityBuilder <T> dte;

            foreach (DataRow dtr in table.Rows)
            {
                dte = DataTableEntityBuilder <T> .CreateBuilder(dtr);

                T t = dte.Build(dtr);
                list.Add(t);
            }
            return(list);
        }
Esempio n. 2
0
        public static DataTableEntityBuilder <T> CreateBuilder(DataRow dr)
        {
            DataTableEntityBuilder <T> dynamicBuilder = new DataTableEntityBuilder <T>();
            DynamicMethod method    = new DynamicMethod("DynamicCreateEntity", typeof(T), new Type[] { typeof(DataRow) }, typeof(T), true);
            ILGenerator   generator = method.GetILGenerator();
            LocalBuilder  result    = generator.DeclareLocal(typeof(T));

            generator.Emit(OpCodes.Newobj, typeof(T).GetConstructor(Type.EmptyTypes));
            generator.Emit(OpCodes.Stloc, result);

            for (int i = 0; i < dr.ItemArray.Length; i++)
            {
                //20140408 shwang修改,因存在datatable列名和类属性定义的大小写问题
                //PropertyInfo pi = typeof(T).GetProperty(dr.Table.Columns[i].ColumnName);
                PropertyInfo pi         = typeof(T).GetProperty(dr.Table.Columns[i].ColumnName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                Label        endIfLabel = generator.DefineLabel();
                if (pi != null && pi.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, pi.PropertyType);
                    generator.Emit(OpCodes.Callvirt, pi.GetSetMethod());
                    generator.MarkLabel(endIfLabel);
                }
            }
            generator.Emit(OpCodes.Ldloc, result);
            generator.Emit(OpCodes.Ret);
            dynamicBuilder.handler = (Load)method.CreateDelegate(typeof(Load));
            return(dynamicBuilder);
        }