简体   繁体   English

自动映射器将继承的对象映射到子对象

[英]Automapper map an inherited object to a child

I have the following classes: 我有以下课程:

Source: 资源:

public class Source
{
    public int Amount { get; set; }
}

Destination: 目的地:

public class Parent
{
    public ChildBase Child { get; set; }
}

public class ChildBase
{

}

public class Child : ChildBase
{
    public int Amount { get; set; }
}

For the map I'm trying to create, I want to map from Source to Parent . 对于我要创建的地图,我想从Source映射到Parent The property on the Parent is defined as ChildBase but I want the map to actually map to Child . Parent上的属性定义为ChildBase但我希望地图实际映射到Child How can I get the mapper to map to Child ? 如何获得映射器以映射到Child

I have a simple map defined as: 我有一个简单的地图定义为:

CreateMap<Source, Parent>()
  .ForMember(d => d.Child, opt => opt.MapFrom(s => s));

CreateMap<Source, Child>();

But obviously this is trying to look for a map with the destination of ChildBase . 但这显然是要寻找目的地为ChildBase的地图。 I tried casting the destination to be Child but that didn't work. 我尝试将目的地设置为“ Child但这没有用。

Any ideas? 有任何想法吗?

You need to use the custom ValueResolver in AutoMapper. 您需要在AutoMapper中使用自定义ValueResolver

Mapper.CreateMap<Source, Parent>()
    .ForMember(p => p.Child, o => o.ResolveUsing(s => new Child { Amount = s.Amount }));

If you want to re-use this logic, you can put the code into a class instead of a lambda expression. 如果要重用此逻辑,可以将代码放入类中,而不是使用lambda表达式。

class SourceToChildValueResolver : ValueResolver<Source, Child>
{
    protected override Child ResolveCore(Source source)
    {
        return new Child { Amount = source.Amount };
    }
}

//register the resolver
CreateMap<Source, Parent>()
    .ForMember(p => p.Child, o => o.ResolveUsing<SourceToChildValueResolver>());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM