AutoMapper将派生类映射到基类型集合的属性

时间:2017-10-16 00:37:32

标签: c# automapper

我正在尝试将两个不同的对象映射到从接口派生的对象。另外,我需要从dtos中将另一个属性映射到派生类型。鉴于此对象结构:

         cfg.CreateMap<StagingDto, Application>()
            .AfterMap((src, dest) => dest.Coverages.Add(new CoverageB()
            {
                HasRecord = src.CoverageB.HasRecord,
                Code = src.Code
            }))
            .AfterMap((src, dest) => dest.Coverages.Add(new CoverageA()
            {
                Current = src.CoverageA.Current,
                Code = src.Code
            }));

下面这个映射有效,但我想知道是否有更好的方法:

lblBookID.Text = grdLWAPBook.SelectedRow.Cells[0].ToString();
        lblStudNum.Text = grdLWAPBook.SelectedRow.Cells[1].ToString();
        lblLWAp.Text = grdLWAPBook.SelectedRow.Cells[2].ToString();
        lblDate.Text = grdLWAPBook.SelectedRow.Cells[3].ToString();
        lblTime.Text = grdLWAPBook.SelectedRow.Cells[4].ToString();enter code here

理想情况下,我不想创建任何扩展方法。

1 个答案:

答案 0 :(得分:0)

对我而言看起来好一点:

cfg.CreateMap<StagingDto, Application>()
    .ForMember(dest => dest.Coverages,
        opt => opt.ResolveUsing(src => new ICoverage[]
        {
            new CoverageA
            {
                Current = src.CoverageA.Current,
                Code = src.Code
            },
            new CoverageB
            {
                HasRecord = src.CoverageB.HasRecord,
                Code = src.Code
            }
        }));