/// <summary> /// 创建DataReaderEntityBuilder对象 /// </summary> /// <param name="dataRecord"></param> /// <returns></returns> public static DataReaderEntityBuilder <TEntity> CreateBuilder(IDataRecord dataRecord) { DataReaderEntityBuilder <TEntity> dynamicBuilder = new DataReaderEntityBuilder <TEntity>(); DynamicMethod method = new DynamicMethod("DynamicCreateEntity", typeof(TEntity), new[] { typeof(IDataRecord) }, typeof(TEntity), true); ILGenerator generator = method.GetILGenerator(); LocalBuilder result = generator.DeclareLocal(typeof(TEntity)); generator.Emit(OpCodes.Newobj, typeof(TEntity).GetConstructor(Type.EmptyTypes)); generator.Emit(OpCodes.Stloc, result); for (int i = 0; i < dataRecord.FieldCount; i++) { PropertyInfo propertyInfo = typeof(TEntity).GetProperty(dataRecord.GetName(i)); 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); }
/// <summary> /// 把DataReader当前数据赋值给一个实体对象,注意方法不负责回收DataReader对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dr"></param> /// <returns></returns> public static T ToEntity <T>(IDataReader dr) where T : class, new() { if (dr == null) { return(default(T)); } var builder = DataReaderEntityBuilder <T> .CreateBuilder(dr); return(builder.Build(dr)); }
/// <summary> /// 把DataReader中数据赋值给一个List对象,注意方法不负责回收DataReader对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dr"></param> /// <returns></returns> public static List <T> ToList <T>(IDataReader dr) where T : class, new() { var list = new List <T>(); if (dr == null) { return(list); } var builder = DataReaderEntityBuilder <T> .CreateBuilder(dr); while (dr.Read()) { list.Add(builder.Build(dr)); } return(list); }