在web开发过程中,有时候为了数据传输的方便,比如:后台需要更新前端的ViewModel,此时我们定义一个与前端ViewModel结构一样的DTO对象,从数据层获取数据后,将数据封装成DTO然后序列化为json传回前端,由于我正在开发的项目中的Model是用DataSet来实现的,不是纯粹的面向对象(如果Model是对象的话可以用AutoMapper来实现转换),所以从数据层获取的都是DataSet或DataTable,这时需要将DataTable转换为DTO对象,DTO对象的属性与DataTable的列之间并不是一一对应的关系,为了转换方便,实现了一个简易的转换类,代码如下:
public class DtObjConverter
{ /// <summary>
/// 将DataTable转换成对象,对象的属性与列同名
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="datatable"></param>
/// <returns></returns>
public List<T> ConvertTo<T>(DataTable datatable) where T : new()
{
List<T> Temp = new List<T>();
try
{
List<string> columnsNames = new List<string>();
foreach (DataColumn DataColumn in datatable.Columns)
columnsNames.Add(DataColumn.ColumnName);
Temp = datatable.AsEnumerable().ToList().ConvertAll<T>(row => getObject<T>(row, columnsNames));
return Temp;
}
catch
{
return Temp;
} } /// <summary>
/// 将DataTable转换成对象,对象的属性会根据map参数进行转换
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="datatable"></param>
/// <param name="map"></param>
/// <returns></returns>
public List<T> ConvertTo<T>(DataTable datatable, Hashtable map) where T : new()
{
List<T> Temp = new List<T>();
try
{
List<string> columnsNames = new List<string>();
foreach (DataColumn DataColumn in datatable.Columns)
columnsNames.Add(DataColumn.ColumnName);
Temp = datatable.AsEnumerable().ToList().ConvertAll<T>(row => getMapObject<T>(row, columnsNames, map));
return Temp;
}
catch
{
return Temp;
} } /// <summary>
/// 根据DataTable生成对象,对象的属性与列同名
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="row"></param>
/// <param name="columnsName"></param>
/// <returns></returns>
public T getObject<T>(DataRow row, List<string> columnsName) where T : new()
{
T obj = new T();
try
{
string columnname = "";
string value = "";
PropertyInfo[] Properties;
Properties = typeof(T).GetProperties();
foreach (PropertyInfo objProperty in Properties)
{
columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());
if (!string.IsNullOrEmpty(columnname))
{
value = row[columnname].ToString();
if (!string.IsNullOrEmpty(value))
{
if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
{
value = row[columnname].ToString().Replace("$", "").Replace(",", "");
objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
}
else
{
value = row[columnname].ToString().Replace("%", "");
objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
}
}
}
}
return obj;
}
catch
{
return obj;
}
} /// <summary>
/// 根据DataTable生成对象,对象的属性会根据map参数进行转换
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="row"></param>
/// <param name="columnsName"></param>
/// <returns></returns>
public T getMapObject<T>(DataRow row, List<string> columnsName, Hashtable map) where T : new()
{
T obj = new T();
try
{
string columnname = "";
string value = "";
PropertyInfo[] Properties;
Properties = typeof(T).GetProperties();
foreach (PropertyInfo objProperty in Properties)
{
string prpertyName = objProperty.Name;
columnname = columnsName.Find(name => name.ToLower() == map[prpertyName].ToString().ToLower());
if (!string.IsNullOrEmpty(columnname))
{
value = row[columnname].ToString();
if (!string.IsNullOrEmpty(value))
{
if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
{
value = row[columnname].ToString().Replace("$", "").Replace(",", "");
objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
}
else
{
value = row[columnname].ToString().Replace("%", "");
objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
}
}
}
}
return obj;
}
catch (Exception e)
{
string error = e.Message;
return obj;
}
} public DataTable ToDataTable<T>(IEnumerable<T> collection)
{
DataTable newDataTable = new DataTable();
Type impliedType = typeof(T);
PropertyInfo[] _propInfo = impliedType.GetProperties();
foreach (PropertyInfo pi in _propInfo)
newDataTable.Columns.Add(pi.Name, pi.PropertyType); foreach (T item in collection)
{
DataRow newDataRow = newDataTable.NewRow();
newDataRow.BeginEdit();
foreach (PropertyInfo pi in _propInfo)
newDataRow[pi.Name] = pi.GetValue(item, null);
newDataRow.EndEdit();
newDataTable.Rows.Add(newDataRow);
}
return newDataTable;
} }
用法:
DtObjConverterConvert convert = new DtObjConverterConvert (); //配置映射
Hashtable map = new Hashtable();
map.Add("Title", "name"); //key为对象属性名,value为表列名
/*----- 此处省略其他字段的添加 -----*/
List<YourDTOModel> dtoModelList = convert.ConvertTo<YourDTOModel>(dt, map);