/// <summary> /// DataReader转换为list /// </summary> /// <typeparam name="T">要转换的类型</typeparam> /// <param name="reader">DataReader对象</param> /// <returns></returns> public static IList <T> DataReaderToList <T>(IDataReader reader) where T : new() { DynamicBuilder <T> builder = DynamicBuilder <T> .CreateBuilder(reader); IList <T> list = new List <T>(); while (reader.Read()) { list.Add(builder.Build(reader)); } reader.Close(); return(list); }
/// <summary> /// DataReader转换为实体 /// </summary> /// <typeparam name="T">转换的类型</typeparam> /// <param name="reader">DataReader对象</param> /// <returns></returns> public static T DataReaderToObject <T>(IDataReader reader) where T : new() { var obj = new T(); if (reader.Read()) { DynamicBuilder <T> builder = DynamicBuilder <T> .CreateBuilder(reader); obj = builder.Build(reader); } else { obj = default(T); } reader.Close(); return(obj); }
public static DynamicBuilder <T> CreateBuilder(IDataRecord dataRecord) { var dynamicBuilder = new DynamicBuilder <T>(); var method = new DynamicMethod("DynamicCreate", typeof(T), new[] { typeof(IDataRecord) }, 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 < dataRecord.FieldCount; i++) { PropertyInfo propertyInfo = typeof(T).GetProperty(dataRecord.GetName(i), BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase); 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, dataRecord.GetFieldType(i)); 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); }