Map RowDataCollection to DTO using AutoMapper

倖福魔咒の 提交于 2019-12-08 07:46:47

问题


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"];

回答1:


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;
    }
}



回答2:


You could do a custom type converter. And, if you're sure the DTO property names will exactly match the DataRow column names, you could probably do a little reflection and have a single type converter.



来源:https://stackoverflow.com/questions/4759611/map-rowdatacollection-to-dto-using-automapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!