关键词:
本文来自: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#反射_两合并更新实体(代码片段)
#region更新实体模型///<summary>///更新实体模型///</summary>///<typeparamname="T">源实体类型</typeparam>///<typeparamname="S">最终合并后返回的实体类型</typeparam>///<paramname="tModel">源数据 查看详情
npoi2.3+泛型+反射根据配置统一解析excel数据到实体的基础方法
解析方法:///<summary>///excel数据解析到实体///</summary>///<typeparamname="T">实体类型</typeparam>///<paramname="sheet">npoi读取到的excel工作表,需要解析的工作表</param>///<paramname="startRow 查看详情
2016-11-2坚持学习day17通过反射自动将datareader转为实体info
通过ADO.net查询到数据库的数据后,通过DataReader转为对象Info publicclassBaseInfo{///<summary>///填充实体///</summary>///<paramname="dr"></param>publicvirtualvoidFill(DataRowdr){PropertyInfo[]ps=t 查看详情
c#知识特性attribute
...等)相关联。特性与程序实体关联后,可在运行时使用“反射”查询特性,获取特性集合方法是GetCustomAttributes();根据约定,所有特性名称都以单词“Attribute”结束,以便将它们与“.NETFramework”中的其他项区分。但是,在代码中... 查看详情
如何将 URL 反射回查询生成器
...报告,并使用OData生成的URL为报告及其标题将它们保存到数据库。以上方法完美运行-客户可以在那里选择表格、条件和过滤器来创建临时报告并将它们保存到数据库中。问题当我的客户回来查看他们创建的报告 查看详情
.netcore反射获取带有自定义特性的类,通过依赖注入根据attribute元数据信息调用对应的方法(代码片段)
...息来调用标记的对应方法。我第一时间想到的就是通过C#反射获取带有CustomAttribute标记的类,然后通过依赖注入(DI)的方式获取对应服务的方法并通过反射动态执行类的方法,从而实现更灵活的编程方式。C#中反射指的是什么?... 查看详情
为任何方法创建 Func 或 Action(在 c# 中使用反射)
...问题描述】:我的应用程序可以根据设置动态加载dll来自数据库(文件、类和方法名)。为了方便、加快和减少反射的使用,我想要一个缓存....遵循使用的想法:MethodInfo.Invoke没有什么表演(Reflect 查看详情
利用泛型和反射实现idatareader转实体
publicstaticTReaderToModel<T>(IDataReaderrow){//1、使用与指定参数匹配最高的构造函数,来创建指定类型的实例TypemodelType=typeof(HShopingCarModel);Tmodel=Activator.CreateInstance<T>();for(inti=0;i<row.FieldCount;i++) 查看详情
[c#基础]使用抽象工厂实现三层和反射
引言昨天加了一天班,今天闲来无事,就在想如何将之前的三层和最近一直在学的设计模式给联系在一起,然后就动手弄了个下面的小demo。项目结构项目各个层实现Wolfy.Model层中有一个抽象类BaseModel.cs,User.cs是用户实体类,继... 查看详情
c#探索之路:反射和特性(代码片段)
C#探索之路(1):反射和特性(一)前言:前段时间将Unity3d中UGUI组件精简复盘落下了帷幕,后期博主可能会从设计模式,部分的算法,以及从UGUI实际操作上、或者从Unity3D部分的一些小游戏Demo上去做文章。但是在... 查看详情
利用反射将idatareader读取到实体类中效率低下的解决办法(代码片段)
...所有的Propertyforeach(PropertyInfoPropertyinproperties)try//取得当前数据库字段的顺序intOrdinal=reader.GetOrdinal(Property.Name);if(reader.GetValue(Ordinal)!=DBNull.Value)//将DataReader读取出来的数据填充到对象实体的属性里Property.SetValue(RowInstance,Con 查看详情
反射入门-浅谈反射用途_根据ado游标对象创建list集合
本人大二菜鸟一只,今天在上课期间有个同学看着C#反射的内容说反射没什么用,一时之间也想不到什么更好的例子,就写了个根据泛型类型和游标反射创建List集合的Demo.首先创建一个用于封装对应数据的entity,代码如下.usingSystem;using... 查看详情
c#中的反射和特性(代码片段)
C#中的反射和特性(二)上一节C#中的反射和特性(一),简单的了解了一下反射是什么,以及部分的特性,接下来继续来了解C#中的其他特性。1.Assembly类Assembly类在System.Reflection命名空间中定义,它允许访问给定程序集... 查看详情
c#中的反射和特性(代码片段)
C#中的反射和特性(二)上一节C#中的反射和特性(一),简单的了解了一下反射是什么,以及部分的特性,接下来继续来了解C#中的其他特性。1.Assembly类Assembly类在System.Reflection命名空间中定义,它允许访问给定程序集... 查看详情
c#用反射实现两个类的对象之间相同属性的值的复制
...复制语句,麻烦还容易漏掉一些,这个时候可以利用c#的反射来实现复制。我们可以写这样一个利用泛型的映射函数。1.适用于创建实体的时候从一个实体作为数据源赋值///<summary>/ 查看详情
javaweb中使用反射机制为数据库中表生成的实体类的的对象赋值?
在数据库中有多张表,有的表含有外键,在javaWeb中对应的某个实体类对象中,就含有其他的对象,如何要进行联合查询,为这个对象赋值,那么,这个对象里面包含的另一个对象怎么赋值?如:同时查询出两张表里面各个字段... 查看详情
c#反射获取数据库字段(代码片段)
staticstringsqlselect="insertinto0(1)values(2)";(这个方法可以适用于任何数据库的插入语句)publicstaticintmanagerRegister<T>(Tfield)stringfieldName="";stringfieldList="";stringfieldValue="";intk=0;Typetf=typeo 查看详情
在 C# 中生成 SQL 的反射?
】在C#中生成SQL的反射?【英文标题】:ReflectiontogenerateSQLinC#?【发布时间】:2011-09-1000:48:48【问题描述】:我有自己的ORM,但我注意到当我得到100k个结果时它的性能很差。对于每次迭代,我都会反映每种类型、它的字段/属性和... 查看详情