码迷,mamicode.com
首页 > 其他好文 > 详细

由DataTable生成实体

时间:2014-11-07 14:31:53      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:ar   os   for   on   cti   ad   amp   new   as   

public static BaseEntity ReceiveEntity(DataRow dr, BaseEntity entity)
{

//声明可以转换为nullable类型的实例
System.ComponentModel.NullableConverter nullableDateTime = new System.ComponentModel.NullableConverter(typeof(DateTime?));
System.ComponentModel.NullableConverter nullableDecimal = new System.ComponentModel.NullableConverter(typeof(decimal?));
if (dr == null)
return null;

BaseEntity baseEntity = (BaseEntity)Activator.CreateInstance(entity.GetType());
foreach (PropertyInfo propertyInfo in entity.GetType().GetProperties())
{
try
{
if (propertyInfo.Name == "NewPassword" || propertyInfo.Name == "DEPT_CLASS_CODE" || propertyInfo.Name == "DEPT_CODE" || propertyInfo.Name == "ReadOnly")
continue;
if (baseEntity.GetType().GetProperty(propertyInfo.Name).PropertyType ==typeof(System.DateTime?))
{
baseEntity.GetType().GetProperty(propertyInfo.Name).SetValue(baseEntity,nullableDateTime.ConvertFromString(dr[propertyInfo.Name].ToString()), null);
}
else if (baseEntity.GetType().GetProperty(propertyInfo.Name).PropertyType == typeof(decimal))
{
baseEntity.GetType().GetProperty(propertyInfo.Name).SetValue(baseEntity, Convert.ToDecimal(dr[propertyInfo.Name].ToString()), null);
}
else if (baseEntity.GetType().GetProperty(propertyInfo.Name).PropertyType == typeof(decimal?))
{
baseEntity.GetType().GetProperty(propertyInfo.Name).SetValue(baseEntity, nullableDecimal.ConvertFromString(dr[propertyInfo.Name].ToString()), null);

}
else
{

baseEntity.GetType().GetProperty(propertyInfo.Name).SetValue(baseEntity, dr[propertyInfo.Name].ToString(), 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;
}

由DataTable生成实体

标签:ar   os   for   on   cti   ad   amp   new   as   

原文地址:http://www.cnblogs.com/startDream/p/4081215.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!