有没有办法使用AutoMapper将 RowDataCollection映射到DTO ?
以下是一个场景: DataRow to Object
user.UserId = row["UserId"];
user.UserName = row["UserName"];
答案 0 :(得分:2)
global.asax配置
Mapper.CreateMap<DataRow, EventCompactViewModel>()
.ConvertUsing(x => (EventCompactViewModel)AutomapperExtensions.DataRowMapper(x, typeof(EventCompactViewModel), null));
数据行映射器
public static object DataRowMapper(DataRow dataRow, Type type, string prefix)
{
try
{
var returnObject = Activator.CreateInstance(type);
foreach (var property in type.GetProperties())
{
foreach (DataColumn key in dataRow.Table.Columns)
{
string columnName = key.ColumnName;
if (!String.IsNullOrEmpty(dataRow[columnName].ToString()))
{
if (String.IsNullOrEmpty(prefix) || columnName.Length > prefix.Length)
{
String propertyNameToMatch = String.IsNullOrEmpty(prefix) ? columnName : columnName.Substring(property.Name.IndexOf(prefix) + prefix.Length + 1);
propertyNameToMatch = propertyNameToMatch.ToPascalCase();
if (property.Name == propertyNameToMatch)
{
Type t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
object safeValue = (dataRow[columnName] == null) ? null : Convert.ChangeType(dataRow[columnName], t);
property.SetValue(returnObject, safeValue, null);
}
}
}
}
}
return returnObject;
}
catch (MissingMethodException)
{
return null;
}
}
答案 1 :(得分:0)
你可以做custom type converter。而且,如果您确定DTO属性名称与DataRow列名称完全匹配,您可能会做一些反射并且只有一个类型转换器。