在程序开发当中,最初的数据库操作我们一般都返回DataRow、DataTable等,对于一般开发人员来说都是比较清楚的,易使用,好理解。当然可以在“高深”一下。我们可以将返回的DataRow、DataTable做一下转换,转换成对应的实体。使用反射技术可以完成此转换。
代码如下:
代码
class
ProcessEntity
{
/// <summary>
/// 填充对象
/// </summary>
/// <param name="dr"></param>
/// <param name="entity"></param>
public static BaseEntity ReceiveEntity(DataRow dr, BaseEntity entity)
{
if (dr == null )
return null ;
BaseEntity baseEntity = (BaseEntity)Activator.CreateInstance(entity.GetType());
foreach (PropertyInfo propertyInfo in entity.GetType().GetProperties())
{
try
{
baseEntity.GetType().GetProperty(propertyInfo.Name).SetValue(baseEntity, dr[propertyInfo.Name], null );
}
catch { }
}
return baseEntity;
}
/// <summary>
/// 填充对象列表
/// </summary>
/// <param name="ds"></param>
/// <param name="entity"></param>
/// <returns></returns>
public static List < BaseEntity > ReceiveEntity(DataSet ds, BaseEntity entity)
{
if ( ! (ds != null && ds.Tables.Count > 0 ))
return null ;
List < BaseEntity > entityList = new List < BaseEntity > ();
foreach (DataRow dr in ds.Tables[ 0 ].Rows)
{
BaseEntity baseEntity = new BaseEntity();
baseEntity = ReceiveEntity(dr, entity);
entityList.Add(baseEntity);
}
return entityList;
}
}
{
/// <summary>
/// 填充对象
/// </summary>
/// <param name="dr"></param>
/// <param name="entity"></param>
public static BaseEntity ReceiveEntity(DataRow dr, BaseEntity entity)
{
if (dr == null )
return null ;
BaseEntity baseEntity = (BaseEntity)Activator.CreateInstance(entity.GetType());
foreach (PropertyInfo propertyInfo in entity.GetType().GetProperties())
{
try
{
baseEntity.GetType().GetProperty(propertyInfo.Name).SetValue(baseEntity, dr[propertyInfo.Name], null );
}
catch { }
}
return baseEntity;
}
/// <summary>
/// 填充对象列表
/// </summary>
/// <param name="ds"></param>
/// <param name="entity"></param>
/// <returns></returns>
public static List < BaseEntity > ReceiveEntity(DataSet ds, BaseEntity entity)
{
if ( ! (ds != null && ds.Tables.Count > 0 ))
return null ;
List < BaseEntity > entityList = new List < BaseEntity > ();
foreach (DataRow dr in ds.Tables[ 0 ].Rows)
{
BaseEntity baseEntity = new BaseEntity();
baseEntity = ReceiveEntity(dr, entity);
entityList.Add(baseEntity);
}
return entityList;
}
}
实现转换的目的主要是为了方便程序开发使用,比如忘记数据库字段名称,不熟悉等。
下载源代码:文件下载