本文来自: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#反射,根据反射将数据库查询数据和实体类绑定,并未实体类赋值的更多相关文章

  1. 用struts2标签如何从数据库获取数据并在查询页面显示。最近做一个小项目,需要用到struts2标签从数据库查询数据,并且用迭代器iterator标签在查询页面显示,可是一开始,怎么也获取不到数据,想了许久,最后发现,是自己少定义了一个变量,也就是var变量。

    最近做一个小项目,需要用到struts2标签从数据库查询数据,并且用迭代器iterator标签在查询页面显示,可是一开始,怎么也获取不到数据,想了许久,最后发现,是自己少定义了一个变量,也就是var变 ...

  2. mongodb基础系列——数据库查询数据返回前台JSP(二)

    上篇博客论述了,数据库查询数据返回前台JSP.博客中主要使用Ajax调用来显示JSON串,来获取其中某一个字段,赋给界面中的某一个控件. 那这篇博客中,我们讲解,把后台List传递JSP展示. Lis ...

  3. C#连接Oracle数据库查询数据

    C#连接Oracle数据库可以实现许多我们需要的功能,下面介绍的是C#连接Oracle数据库查询数据的方法,如果您对C#连接Oracle数据库方面感兴趣的话,不妨一看. using System; u ...

  4. mongodb基础系列——数据库查询数据返回前台JSP(一)

    经过一段时间停顿,终于提笔来重新整理mongodb基础系列博客了. 同时也很抱歉,由于各种原因,没有及时整理出,今天做了一个demo,来演示,mongodb数据库查询的数据在JSP显示问题. 做了一个 ...

  5. SpringMVC——项目启动时从数据库查询数据

    SpringMVC项目中遇到这样的问题: 1.很多数据字典需要从数据库中查询: 2.懒得修改SQL语句: 3.想在项目中声明静态变量存储数据字典,但是希望这个字典可以在项目启动时进行加载. 当遇到这样 ...

  6. python自动化测试之mysql5.0版本数据库查询数据时出现乱码问题分析

    1.确保数据库编码是utf8编码.若不是,请将my.ini的client,mysql,mysqld三个字段下面添加default-character-set = utf8,这样可以永久改变在新建数据库 ...

  7. MySQL 数据库查询数据,过滤重复数据保留一条数据---(MySQL中的row_number变相实现方法)

    转自: http://www.maomao365.com/?p=10564 摘要: 下文讲述MySQL数据库查询重复数据时,只保留一条数据的方法 实现思路: 在MySQL数据库中没有row_numbe ...

  8. koa 基础(二十一)nodejs 操作mongodb数据库 --- 查询数据

    1.app.js /** * nodejs 操作mongodb数据库 * 1.安装 操作mongodb * cnpm install mongodb --save * 2.引入 mongodb 下面的 ...

  9. TreeView和ListView数据库查询数据联动操作

    好久不用了,重新整理下放这里以备需要使用,功能见图 数据库表结构 定义TreeView addObject中data存储的记录集 type PNode = ^TNode; TNode = record ...

随机推荐

  1. IL接口和类的属性

    上一篇文章学习了IL的入门,接下来我们再通过两个例子来了解下类的属性.构造函数以及接口的使用 一.类的属性.构造函数 1.先看下我们要构建的类的C#代码,然后再进行IL的实现,示例代码如下: [Ser ...

  2. 使用命令 gradle uploadArchives 的异常: Unable to initialize POM pom-default.xml: Failed to validate POM for project

    在使用:gradle uploadArchives 命令对项目进行上传maven时,常常遇到如下报错: 这时候要仔细的检查一下build.gradle文件中的dependencies内容,很多时候是由 ...

  3. php实现设计模式之 模板方法模式

    <?php /** * 模板模式 * * 定义一个操作中的算法骨架,而将一些步骤延迟到子类中,使得子类可以不改变一个算法的结构可以定义该算法的某些特定步骤 * */ abstract class ...

  4. Why AlloyFinger is so much smaller than hammerjs?

    AlloyFinger is the mobile web gesture solution at present inside my company, major projects are in u ...

  5. WCF+Restfull服务 提交或获取数据时数据大小限制问题解决方案

    近日在使用wcf的restfull架构服务时遭遇到了提交大数据的问题. 大数据包含两种情形: 1)单条数据量过大. 2)提交或获取的数据条数过多. 在测试时发现,默认设置下当单条JSON数据大于30K ...

  6. 安装cocoapods以及更新cocoapods

    安装 1.设置ruby的软件源 这是因为ruby的软件源rubygems.org因为使用亚马逊的云服务,被我天朝屏蔽了,需要更新一下ruby的源,过程如下: gem sources -l #(查看当前 ...

  7. 简单配置 nginx 反向代理

    # Nginx 域名反向代理配置# 安装nginx yum install nginx -y# 修改配置文件 进入配置文件目录 cd /etc/nginx/conf.d 新建配置文件以.conf结尾 ...

  8. 5-4 bash脚本编程之三 条件判断及算术运算

    1. 反引号是引用执行结果,并非是返回值 如下是错误的,结果是一行行记录,不是返回值 放大为: 练习 2. shell中如何进行算术运算 A=3 B=4 1. let算术运算表达式 2. $[算术运算 ...

  9. 2-kvm创建快照以及网卡绑定

    kvm创建快照以及网卡绑定 创建node1 查看node1 进入到kvm的配置文件里 将rhcs文件复制一份取名为node1.xml 通过这个命令随机生成一个uuid 然后就进入node1.xml里修 ...

  10. USACO . Your Ride Is Here

    Your Ride Is Here It is a well-known fact that behind every good comet is a UFO. These UFOs often co ...