Welcome 微信登录

首页 / 网页编程 / ASP.NET / 如何将DataRow转换成相应的对象

如何将DataRow转换成相应的对象2013-11-28 博客园 JasenKin一直以来对框架非常感兴趣,对大多数框架(目前本人看过的)来说一般分为三个部分:

(1): 拼接SQL语句(反射)。

(2):执行CRUD操作,获取相应的DataTable、DataSet等等。

(3) :将相应的DataTable、DataSet转换成对象(反射)。

因此可以将上述3个部分各个击破,一步一步来 实现自己的框架,看的框架多了,也就成了路。反射在这里面被淋漓尽致的运用,哈哈,站在款哥的肩膀 上......

(一)通用以及泛型转换代码

先看下面关于将DataRow转换成相应的对象(通用以及 泛型操作)的方法(这里仅仅是对DataRow进行转换,对于将DataTable转换成对象集合,思路基本差不多,因 此本例里不再对其他的进行相关代码的编写):

public class Mapper{public static object ToEntity(DataRow adaptedRow, Type entityType){if (entityType == null || adaptedRow == null){return null;}object entity = Activator.CreateInstance(entityType);CopyToEntity(entity, adaptedRow);return entity;}public static T ToEntity<T>(DataRow adaptedRow, T value) where T:new(){T item = new T();if (value == null || adaptedRow == null){return item;}item = Activator.CreateInstance<T>();CopyToEntity(item, adaptedRow);return item;}public static void CopyToEntity(object entity, DataRow adaptedRow){if (entity == null || adaptedRow == null){return;}PropertyInfo[] propertyInfos = entity.GetType().GetProperties();foreach (PropertyInfo propertyInfo in propertyInfos){if (!CanSetPropertyValue(propertyInfo, adaptedRow)){continue;}try{if (adaptedRow[propertyInfo.Name] is DBNull){propertyInfo.SetValue(entity, null, null);continue;}SetPropertyValue(entity, adaptedRow, propertyInfo);}finally{}}}private static bool CanSetPropertyValue(PropertyInfo propertyInfo, DataRow adaptedRow){if (!propertyInfo.CanWrite){return false;}if (!adaptedRow.Table.Columns.Contains(propertyInfo.Name)){return false;}return true;}private static void SetPropertyValue(object entity, DataRow adaptedRow, PropertyInfo propertyInfo){if (propertyInfo.PropertyType == typeof(DateTime?) ||propertyInfo.PropertyType == typeof(DateTime)){DateTime date = DateTime.MaxValue;DateTime.TryParse(adaptedRow[propertyInfo.Name].ToString(),CultureInfo.CurrentCulture, DateTimeStyles.None, out date);propertyInfo.SetValue(entity, date, null);}else{propertyInfo.SetValue(entity, adaptedRow[propertyInfo.Name], null);}}}
以上的代码主要是针对将DataRow转换成相应的对象,方法为

(1)public static object ToEntity(DataRow adaptedRow, Type entityType)
(2)public static T ToEntity<T>(DataRow adaptedRow, T value) where T:new()