[英]AutoMapper Map derived classes to property of base type collection
I'm trying to map two different objects to objects that are derived from an interface. 我正在尝试将两个不同的对象映射到从接口派生的对象。 Additionally, I need to have another property mapped to the derived types from the dtos. 另外,我需要从dtos中将另一个属性映射到派生类型。 Given this object structure: 鉴于此对象结构:
public interface ICoverage
{
string Name { get; set; }
string Code { get; set; }
}
public class CoverageA : ICoverage
{
public string Name { get; set; }
public string Code { get; set; }
public string Current { get; set; }
}
public class CoverageB : ICoverage
{
public string Name { get; set; }
public string Code { get; set; }
public bool HasRecord { get; set; }
}
public class Application
{
public int ApplicationId { get; set; }
public string Code { get; set; }
public List<ICoverage> Coverages { get; set; }
public Application()
{
Coverages = new List<ICoverage>();
}
}
public class StagingDto
{
public string Referrer { get; set; }
public string Code { get; set; }
public CoverageADto CoverageA { get; set; }
public CoverageBDto CoverageB { get; set; }
}
public class CoverageADto
{
public string Current { get; set; }
}
public class CoverageBDto
{
public bool HasRecord { get; set; }
}
This mapping below works but I am wondering if there is a better way to do it: 下面的这个映射有效,但我想知道是否有更好的方法:
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
}));
Ideally I'd like to stay away from having to create any extension method. 理想情况下,我不想创建任何扩展方法。
For me it looks a bit better: 对我来说它看起来好一点:
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
}
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.