[转]C#反射,根据反射将数据库查询数据和实体类绑定,并未实体类赋值
本文来自:http://www.cnblogs.com/mrchenzh/archive/2010/05/31/1747937.html
/*****************************************
* 说明:利用反射将数据库查询的内容自动绑定
* 到实体类
*
* 时间: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", con);
//objAdapter.Fill(ds);
#endregion
#region 手动构建DataSet
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
DataRow row = dt.NewRow();
row["ID"] = 1;
row["Name"] = "灰太狼";
dt.Rows.Add(row);
ds.Tables.Add(dt);
#endregion
List<Student> students = new List<Student>();
foreach (DataRow dataRow in ds.Tables[0].Rows)
{
Student stu = new Student();
Utility.ConvertToEntity(stu, row);
students.Add(stu);
}
foreach (Student student in students)
{
Console.WriteLine(student.Name);
}
}
}
#endregion
#region 实体类
/// <summary>
/// 实体类,需要在属性
/// 上添加自定义特性
/// 每个实体类对应数据表里
/// 的一个字段,注意,自定义特性里的参数
/// 一定要和数据表里的字段一一对应,
/// 否则就反射不到了!
/// </summary>
public class Student
{
[DataContextAttribute("ID")]
public int ID { get; set; }
[DataContext("Name")]
public string Name { get; set; }
}
#endregion
#region 自定义特性
/// <summary>
/// 自定义特性
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class DataContextAttribute : Attribute
{
/// <summary>
/// 自定义特性
/// </summary>
/// <param name="fieldName">数据表字段名称</param>
public DataContextAttribute(string property) { this.Property = property; }
/// <summary>
/// 数据表字段属性(实体属性)
/// </summary>
public string Property { get; set; }
}
#endregion
#region 反射
public class Utility
{
/// <summary>
/// 将DataRow转换成实体
/// </summary>
/// <param name="obj">实体</param>
/// <param name="row">数据表一行数据</param>
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
}
[转]C#反射,根据反射将数据库查询数据和实体类绑定,并未实体类赋值的更多相关文章
- 用struts2标签如何从数据库获取数据并在查询页面显示。最近做一个小项目,需要用到struts2标签从数据库查询数据,并且用迭代器iterator标签在查询页面显示,可是一开始,怎么也获取不到数据,想了许久,最后发现,是自己少定义了一个变量,也就是var变量。
最近做一个小项目,需要用到struts2标签从数据库查询数据,并且用迭代器iterator标签在查询页面显示,可是一开始,怎么也获取不到数据,想了许久,最后发现,是自己少定义了一个变量,也就是var变 ...
- mongodb基础系列——数据库查询数据返回前台JSP(二)
上篇博客论述了,数据库查询数据返回前台JSP.博客中主要使用Ajax调用来显示JSON串,来获取其中某一个字段,赋给界面中的某一个控件. 那这篇博客中,我们讲解,把后台List传递JSP展示. Lis ...
- C#连接Oracle数据库查询数据
C#连接Oracle数据库可以实现许多我们需要的功能,下面介绍的是C#连接Oracle数据库查询数据的方法,如果您对C#连接Oracle数据库方面感兴趣的话,不妨一看. using System; u ...
- mongodb基础系列——数据库查询数据返回前台JSP(一)
经过一段时间停顿,终于提笔来重新整理mongodb基础系列博客了. 同时也很抱歉,由于各种原因,没有及时整理出,今天做了一个demo,来演示,mongodb数据库查询的数据在JSP显示问题. 做了一个 ...
- SpringMVC——项目启动时从数据库查询数据
SpringMVC项目中遇到这样的问题: 1.很多数据字典需要从数据库中查询: 2.懒得修改SQL语句: 3.想在项目中声明静态变量存储数据字典,但是希望这个字典可以在项目启动时进行加载. 当遇到这样 ...
- python自动化测试之mysql5.0版本数据库查询数据时出现乱码问题分析
1.确保数据库编码是utf8编码.若不是,请将my.ini的client,mysql,mysqld三个字段下面添加default-character-set = utf8,这样可以永久改变在新建数据库 ...
- MySQL 数据库查询数据,过滤重复数据保留一条数据---(MySQL中的row_number变相实现方法)
转自: http://www.maomao365.com/?p=10564 摘要: 下文讲述MySQL数据库查询重复数据时,只保留一条数据的方法 实现思路: 在MySQL数据库中没有row_numbe ...
- koa 基础(二十一)nodejs 操作mongodb数据库 --- 查询数据
1.app.js /** * nodejs 操作mongodb数据库 * 1.安装 操作mongodb * cnpm install mongodb --save * 2.引入 mongodb 下面的 ...
- TreeView和ListView数据库查询数据联动操作
好久不用了,重新整理下放这里以备需要使用,功能见图 数据库表结构 定义TreeView addObject中data存储的记录集 type PNode = ^TNode; TNode = record ...
随机推荐
- 为Guid数据类型的属性(property)赋值
先来看看数据库表中的字段设计: 在数据库的数据类型为uniqueidentifier. 而在程序中对应的数据类型为GUID. property有get和set,也就是说能获取值也可以赋值.
- Navisworks Api Tool
用Google 翻译的..做个参考 None 无有效的选择 Select 选择 SelectBox 选择框 RedlineFreehand 红线写意 RedlineLine 红线线 Redli ...
- C/C++ Memory Layout
参考 http://www.cnblogs.com/skynet/archive/2011/03/07/1975479.html
- Golang接口(interface)三个特性(译文)
The Laws of Reflection 原文地址 第一次翻译文章,请各路人士多多指教! 类型和接口 因为映射建设在类型的基础之上,首先我们对类型进行全新的介绍. go是一个静态性语言,每个变量都 ...
- 关于Three.js基本几何形状之SphereGeometry球体学习
一.有关球体SphereGeometry构造函数参数说明 <1>.SphereGeometry(radius, widthSegments, heightSegments, phiStar ...
- linux定制
http://cc.bingj.com/cache.aspx?q=OpenEmbedded+clfs&d=4706495287069596&mkt=zh-CN&setlang= ...
- 基于JQuery实现的文本框自动填充功能
1. 实现的方法 /* * js实现的文本框的自动完成功能 */ function doAutoComplete(textid,dataid,url){ $("#" + texti ...
- 生成freeswitch事件的几种方式
本文描述了生成freeswitch事件的几种方式,这里记录下,也方便我以后查阅. 操作系统:debian8.5_x64 freeswitch 版本 : 1.6.8 在freeswitch代码中加入事件 ...
- [Erlang 0125] Know a little Erlang opcode
Erlang源代码编译为beam文件,代码要经过一系列的过程(见下面的简图),Core Erlang之前已经简单介绍过了Core Erlang,代码转换为Core Erlang,就容易拨开一些语法糖的 ...
- hbase开发实例
1.put/checkAndPut package com.testdata; import java.io.IOException; import org.apache.hadoop.conf.Co ...