
/*****************************************
* 说明:利用反射将数据库查询的内容自动绑定
* 到实体类
*
* 时间:1:49 2009-9-19
*
* 程序员:王文壮
* ***************************************/
/****************数据库脚本***************
* create database MySchool
* go
* use MySchool
* go
* create table Student
* (
* ID int identity primary key,
* Name varchar(10)
* )
* ****************************************/
using System;
using System.Reflection;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
namespace ReflectionDemo
{
#region Main
class Program
{
static void Main(string[] args)
{
DataSet ds = new DataSet();
#region 连接数据库构建DataSet
//SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=MySchool;Integrated Security=True");
//SqlDataAdapter objAdapter = new SqlDataAdapter("Select * from student
/// /// 数据表字段属性(实体属性) ///
public string Property { get; set; }
}
#endregion
#region 反射
public class Utility
{
/// /// 将DataRow转换成实体 ///
/// 实体
/// 数据表一行数据
public static void ConvertToEntity(object obj, DataRow row)
{
///得到obj的类型
Type type = obj.GetType();
///返回这个类型的所有公共属性
PropertyInfo[] infos = type.GetProperties();
///循环公共属性数组
foreach (PropertyInfo info in infos)
{
///返回自定义属性数组
object[] attributes = info.GetCustomAttributes(typeof(DataContextAttribute), false);
///将自定义属性数组循环
foreach (DataContextAttribute attribute in attributes)
{
///如果DataRow里也包括此列
if (row.Table.Columns.Contains(attribute.Property))
{
///将DataRow指定列的值赋给value
object value = row[attribute.Property];
///如果value为null则返回
if (value == DBNull.Value) continue;
///将值做转换
if (info.PropertyType.Equals(typeof(string)))
{
value = row[attribute.Property].ToString();
}
else if (info.PropertyType.Equals(typeof(int)))
{
value = Convert.ToInt32(row[attribute.Property]);
}
else if (info.PropertyType.Equals(typeof(decimal)))
{
value = Convert.ToDecimal(row[attribute.Property]);
}
else if (info.PropertyType.Equals(typeof(DateTime)))
{
value = Convert.ToDateTime(row[attribute.Property]);
}
else if (info.PropertyType.Equals(typeof(double)))
{
value = Convert.ToDouble(row[attribute.Property]);
}
else if (info.PropertyType.Equals(typeof(bool)))
{
value = Convert.ToBoolean(row[attribute.Property]);
}
///利用反射自动将value赋值给obj的相应公共属性
info.SetValue(obj, value, null);
}
}
}
}
}
#endregion
}
