CSFramework.DB.DbTools类下载
数据转换工具,DbDataReader/DataRow转实体对象
C# 全选
using System;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Reflection;
namespace CSFramework.DB
{
/// <summary>
/// 数据转换工具,DbDataReader/DataRow转实体对象
/// </summary>
public static class DbTools
{
private static void SetValue(object obj, PropertyInfo p, string fname, object fvalue, Type fType)
{
object tv;
//处理byte数组转日期,如SqlServer的Timestamp类型
//数据类型是byte[],且对象属性类型是DateTime
if (p.PropertyType == typeof(DateTime) && fType == typeof(byte[]))
{
long lo = Math.Abs(BitConverter.ToInt64((byte[])fvalue, 0));
DateTime rt = DateTime.FromBinary(lo);
p.SetValue(obj, rt, null);
}
//数组类型,单独处理
else if (p.PropertyType.IsArray)
{
if (fvalue == DBNull.Value) //特殊处理DBNull类型
p.SetValue(obj, null, null);
else
p.SetValue(obj, fvalue, null);
}
//bool类型,特殊处理
else if (p.PropertyType == typeof(Boolean))
{
string[] bTrue = "YES,Y,T,1,TRUE".Split(',');
string[] bFalse = "NO,N,F,0,FALSE".Split(',');
var o = bTrue.Where(e => e.ToUpper() == fvalue.ToString().Trim().ToUpper()).FirstOrDefault();
if (!String.IsNullOrEmpty(o))
p.SetValue(obj, true, null);
else
p.SetValue(obj, false, null);
}
//处理对象数据类型
else if (p.PropertyType == typeof(System.Object))
{
p.SetValue(obj, fvalue, null);
}
else
{
//普通数据类型,赋值操作
if (fvalue == null || String.IsNullOrWhiteSpace(fvalue.ToString()))//空值
tv = p.PropertyType.IsValueType ? Activator.CreateInstance(p.PropertyType) : null;//值类型
else
tv = System.ComponentModel.TypeDescriptor.GetConverter(p.PropertyType).ConvertFromString(fvalue.ToString());//创建对象
p.SetValue(obj, tv, null);
}
}
/// <summary>
/// DbDataReader转换为对象实例,(字段名称优先)
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="row">DbDataReader实例</param>
/// <returns></returns>
public static T Convert2Object<T>(DbDataReader row) where T : new()
{
T obj = new T();
Type type = typeof(T);
string fname; object fvalue; Type fType;
//循环记录的字段名称
for (int i = 0; i < row.FieldCount; i++)
{
fname = row.GetName(i);//字段名
fvalue = row.GetValue(i);//字段的值
fType = row.GetFieldType(i);//字段的数据类型
//根据字段名称获取对象的属性
PropertyInfo p = type.GetProperty(fname, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (p != null) SetValue(obj, p, fname, fvalue, fType);
}
return obj;
}
/// <summary>
/// DataRow转换为对象实例
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="row">DataRow实例</param>
/// <returns></returns>
public static T Convert2Object<T>(DataRow row) where T : new()
{
T obj = new T();
Type type = typeof(T);
string fname; object fvalue; Type fType;
for (int i = 0; i < row.Table.Columns.Count; i++)
{
fname = row.Table.Columns[i].ColumnName;//字段名
fvalue = row[fname];//值
fType = row.Table.Columns[i].DataType;//字段数据类型
PropertyInfo p = type.GetProperty(fname, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (p != null) SetValue(obj, p, fname, fvalue, fType);
}
return obj;
}
}
}
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网