首页 > 代码库 > 由DataTable生成实体

由DataTable生成实体

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生成实体