【IT168技术文档】
ORM(Object/Relation Mapping对象-关系数据库映射)其中的一个功能是将数据源数据赋值给实体。实现方法是利用自定义属性和.NET反射机制。例如:
1 public class LWordEntity
2 {
3 /**//// <summary>
4 /// 获取或设置留言 ID
5 /// </summary>
6 [DataColumn(ColumnName = "LWordUID")]
7 public int LWordUID
8 {
9 //
10 }
11
12 /**//// <summary>
13 /// 获取或设置发送用户
14 /// </summary>
15 [DataColumn(ColumnName = "PostUser")]
16 public string PostUser
17 {
18 //
19 }
20
21 /**//// <summary>
22 /// 获取或设置发送时间
23 /// </summary>
24 [DataColumn(ColumnName = "PostTime")]
25 public DateTime PostTime
26 {
27 //
28 }
29
30 /**//// <summary>
31 /// 获取或设置文本内容
32 /// </summary>
33 [DataColumn(ColumnName = "TextContent")]
34 public string TextContent
35 {
36 //
37 }
38 }
DataColumn是自定义的属性类,代码并不复杂所以在这里也就省略了。接下来需要通过反射读取自定义属性,并赋值。代码如下:
1 public void PutEntityProperties(object objEntity, DbDataReader dr)
2 {
3 // 获取实体类型
4 Type objType = objEntity.GetType();
5
6 // 获取属性信息
7 PropertyInfo[] propInfoList = objType.GetProperties();
8
9 if (propInfoList == null || propInfoList.Length <= 0)
10 return;
11
12 foreach (PropertyInfo propInfo in propInfoList)
13 {
14 object[] colAttrList = propInfo.GetCustomAttributes(typeof(DataColumnAttribute), false);
15
16 // 未标记 DataColumn 属性
17 if (colAttrList == null || colAttrList.Length <= 0)
18 continue;
19
20 // 获取数据列属性
21 DataColumnAttribute colAttr = colAttrList[0] as DataColumnAttribute;
22
23 int ordinal = -1;
24
25 try
26 {
27 // 获取数据列序号
28 ordinal = dr.GetOrdinal(colAttr.ColumnName);
29 }
30 catch (Exception ex)
31 {
32 throw new MappingException(
33 String.Format("{0} 未找到该数据列( Cannot Found this Column {0} )", colAttr.ColumnName), ex);
34 }
35
36 // 获取数据列值
37 object objValue = dr.GetValue(ordinal);
38
39 if (objValue is DBNull)
40 {
41 // 将 null 值设置到属性
42 propInfo.SetValue(objEntity, null, null);
43 }
44 else
45 {
46 // 将值设置到属性
47 propInfo.SetValue(objEntity, objValue, null);
48 }
49 }
50 }
51