1

AutoMapper を使用してRowDataCollectionを DTOにマップする方法はありますか?

ここにシナリオがあります: DataRow to Object

user.UserId = row["UserId"];
user.UserName = row["UserName"];
4

2 に答える 2

2

glbal.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;
    }
}
于 2011-01-29T06:32:10.890 に答える
0

カスタム型コンバーターを実行できます。また、DTO プロパティ名が DataRow 列名と正確に一致することが確実な場合は、おそらく少しリフレクションを行って、単一の型コンバーターを使用できます。

于 2011-01-21T21:16:41.980 に答える