public static T DataReaderToEntity<T>(IDataReader dr, T entity) { try { PropertyInfo[] pilist = entity.GetType().GetProperties(); foreach (PropertyInfo pi in pilist) { for (int i = 0; i < dr.FieldCount; i++) { if (pi.Name.Equals(dr.GetName(i))) { pi.SetValue(entity, Convert.ChangeType(dr[i], pi.PropertyType), null); } } } return entity; } catch { return default(T); } }
上面的方法利用反射读取SqlDataReader对应值。红色部分转换为相应的类型