Use AutoMapper to map from an interface to a concrete type

后端 未结 1 1116
庸人自扰
庸人自扰 2021-01-02 06:01

I\'ve created a dotNetFiddle that demonstrates the question here.


Here\'s a simplified example of what I\'m trying to do... let\'s say I have an the followin

相关标签:
1条回答
  • 2021-01-02 06:24

    Question 1: Not that I am aware of.

    Question 2: When using the .ConstructUsing() make sure you return the mapped object you are after rather than a fresh instance.

    e.g.

    Mapper.Initialize(config =>
    {
        config.CreateMap<IPerson, PersonDto>()
            .Include<IModelPerson, ModelPersonDto>()
            .ConstructUsing((IPerson person) => 
            {
                if (person is IModelPerson) return Mapper.Map<ModelPersonDto>(person);
    
                throw new InvalidOperationException("Unknown person type: " + person.GetType().FullName);
            })
            ;
    
        config.CreateMap<IModelPerson, ModelPersonDto>();
    });
    
    0 讨论(0)
提交回复
热议问题