ASP.NET2.0:AdventureWorks贸易系统
使用泛型程序实现输出转换
当获取了作为输出的SqlDataReader对象后,下一步是将输出内容转换为可发送到业务逻辑层的泛型集合。
GetProductCategories()方法利用辅助类DataAccessHelper(如示例2所示)将SqlDataReader对象内容转换为对象。
示例2:实现DataAccessHelper类
using System;在GetProductCategories()方法内部,首先声明了一个DataColumnMapping数组,该数组中包括ProductCategory表列与ProductCategory对象属性之间的所有映射信息:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.Common;
using System.Reflection;
using System.Collections;
namespace AdventureWorksTraderDataAccess
{
public class DataAccessHelper
{
static public object PopulateEntity(object entity, DataColumnMapping[] mappings, IDataReader reader)
{
foreach (DataColumnMapping mapping in mappings)
{
int ordinalPosition = 0;
try
{
ordinalPosition = reader.GetOrdinal(mapping.SourceColumn);
}
catch (IndexOutOfRangeException ex)
{
throw new PropertyColumnMappingException(mapping.SourceColumn +
" is not a valid SourceColumn", ex);
}
object propertyValue = reader.GetValue(ordinalPosition);
if (propertyValue != DBNull.Value)
{
if (mapping.DataSetColumn == "ID")
{
Nullable<int> tempValue = (int)propertyValue;
propertyValue = tempValue;
}
object[] param = { propertyValue };
try
{
entity.GetType().InvokeMember(mapping.DataSetColumn, BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.Static, null, entity, param);
}
catch (Exception e)
{
throw new PropertyColumnMappingException
(GetPropertyColumnMappingExceptionMessage(mapping), e);
}
}
}
return entity;
}
private static string GetPropertyColumnMappingExceptionMessage
(DataColumnMapping mapping)
{
return "Could not populate " + mapping.DataSetColumn +
" property from the " + mapping.SourceColumn + " database column";
}
}
}
private DataColumnMapping[] mappings = new DataColumnMapping[] {
new DataColumnMapping("ProductCategoryID", "ProductCategoryID"),
new DataColumnMapping("Name", "Name"),
new DataColumnMapping("rowguid", "Rowguid"),
new DataColumnMapping("ModifiedDate", "ModifiedDate")};
当调用PopulateEntity()时,需要提供ProductCategory对象实例,DataColumnMapping数组以及包括执行存储过程所得输出的SqlDataReader对象:ProductCategory category = (ProductCategory)DataAccessHelper.PopulateEntity(temp, mappings, reader);PopulateEntity()方法将SqlDataReader对象的每一行转换为具有适当属性值的ProductCategory对象。
0
相关文章