Automapper SetValue基于Property Name

时间:2016-03-22 20:22:58

标签: c# automapper

尝试使用AutoMapper根据属性名称设置属性值...

DTO ......

/// <summary>
/// DTO for the Performance Overview Report
/// </summary>
public class PerformanceOverviewDto
{
    public OverviewDto Summary1  { get; set; }
    public OverviewDto Summary2 { get; set; }
}

/// <summary>
/// DTO for the WorkIn Overview 
/// </summary>
public class OverviewDto : MetricOverviewDto
{
    /// <summary>
    /// Total Hours for the Period
    /// </summary>
    public Decimal? TotalHours { get; set; }

    /// <summary>
    /// Average Hours per working day 
    /// </summary>
    public string AvgHoursPerWorkingDay { get; set; } 
}

单位是我的ViewModel中用于标记的额外属性

public class MetricsOverviewModel
{
    public MetricSummaryModel Summary1 { get; set; }
    public MetricSummaryModel Summary2 { get; set; }
}

public class MetricSummaryModel
{
    public string MinForPeriod { get; set; }
    public string MaxForPeriod { get; set; }
    public string Units { get; set; }
    public decimal TotalHours { get; set; }
    public string AvgHoursPerWorkingDay { get; set; }
    public IEnumerable<MetricSeriesOverviewDto> AllValuesPerTimePeriod { get; set; }
}

对于“Summary2”..我想覆盖Units的默认值..

public class WebAutoMapperProfile : Profile
{
    protected override void Configure()
    {
        CreateMap<OverviewDto, MetricSummaryModel>()
            .ForMember(prop => prop.Units, opt => opt.UseValue(Strings.HoursinShort));
        CreateMap<PerformanceOverviewDto, MetricsOverviewModel>()
            .ForMember(prop => prop.Summary1.Units, opt => opt.UseValue(Strings.PercentSymbol));
    }
}

我正在...... 表达式'prop =&gt; prop.Summary1.Units'必须解析为顶级成员而不是任何子对象的属性。请改用子类型或AfterMap选项上的自定义解析器。

提前致谢! 基思。

1 个答案:

答案 0 :(得分:0)

查看DTO的代码会很有帮助,但我想你会想要以下内容:

CreateMap<OverviewDto, MetricSummaryModel>()
    .ForMember(prop => prop.Units, opt => opt.UseValue(Strings.HoursinShort));
CreateMap<PerformanceOverviewDto, MetricsOverviewModel>()
    .AfterMap((src, dest) => dest.Summary1.Units = Strings.PercentSymbol);

基本上,如果您要从PerformanceOverviewDto - &gt;进行映射MetricsOverviewModelthis,这会使用第一个CreateMapOverviewDto映射到MetricSummary,然后使用AfterMap覆盖Strings.HoursinShort Strings.PercentSymbol }}