地图RowDataCollection使用AutoMapper DTO [英] Map RowDataCollection to DTO using AutoMapper
本文介绍了地图RowDataCollection使用AutoMapper DTO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法来映射一个 RowDataCollection到DTO 使用 AutoMapper ?
下面是一个场景:的DataRow对象
user.UserId =行[用户ID];
user.UserName =行[用户名];
解决方案
glbal.asax配置
Mapper.CreateMap< DataRow的,EventCompactViewModel>()
.ConvertUsing(X =>(EventCompactViewModel)AutomapperExtensions.DataRowMapper(X的typeof(EventCompactViewModel),NULL));
数据行映射
公共静态对象DataRowMapper(DataRow的数据行,类型类型,字符串preFIX)
{
尝试
{
变种返回object = Activator.CreateInstance(类型);
的foreach(在type.GetProperties变种属性())
{
的foreach(在dataRow.Table.Columns的DataColumn键)
{
字符串COLUMNNAME = key.ColumnName;
如果(!String.IsNullOrEmpty(数据行[COLUMNNAME]的ToString()))
{
如果(String.IsNullOrEmpty(preFIX)|| columnName.Length> prefix.Length)
{
字符串propertyNameToMatch = String.IsNullOrEmpty(preFIX)? COLUMNNAME:columnName.Substring(property.Name.IndexOf(preFIX)+ prefix.Length + 1);
propertyNameToMatch = propertyNameToMatch.ToPascalCase();
如果(property.Name == propertyNameToMatch)
{
类型t = Nullable.GetUnderlyingType(property.PropertyType)? property.PropertyType;
对象safeValue =(数据行[COLUMNNAME] == NULL)?空:Convert.ChangeType(数据行[COLUMNNAME],T);
property.SetValue(返回object,safeValue,NULL);
}
}
}
}
}
返回返回object;
}
赶上(的MissingMethodException)
{
返回null;
}
}
Is there a way to map a RowDataCollection to DTO using AutoMapper?
Here is a scenario: DataRow to Object
user.UserId = row["UserId"];
user.UserName = row["UserName"];
解决方案
glbal.asax configuration
Mapper.CreateMap<DataRow, EventCompactViewModel>()
.ConvertUsing(x => (EventCompactViewModel)AutomapperExtensions.DataRowMapper(x, typeof(EventCompactViewModel), null));
Data row mapper
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;
}
}
这篇关于地图RowDataCollection使用AutoMapper DTO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文