一直以來對框架非常感興趣,對大多數框架(目前本人看過的)來說一般分為三個部分:
(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()