如何使用显式成员映射为多态配置 AutoMapper?

How to configure AutoMapper for Polymorphism with explicit member mapping?(如何使用显式成员映射为多态配置 AutoMapper?)
本文介绍了如何使用显式成员映射为多态配置 AutoMapper?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下基本情况:

Mapper.CreateMap<FromBase, ToBase>()
        .Include<FromD1, ToD1>()
        .Include<FromD2, ToD2>();

Mapper.CreateMap<FromD1, ToD1>()
        .ForMember( m => m.P0, a => a.MapFrom( x => x.Prop0 ) )
        .ForMember( m => m.P1, a => a.MapFrom( x => x.Prop1 ) );

Mapper.CreateMap<FromD2, ToD2>()
        .ForMember( m => m.P0, a => a.MapFrom( x => x.Prop0 ) )
        .ForMember( m => m.P2, a => a.MapFrom( x => x.Prop2 ) );

Mapper.AssertConfigurationIsValid();

FromBase[] froms = {
        new FromD1() { Prop0 = 10, Prop1 = 11 },
        new FromD2() { Prop0 = 20, Prop2 = 22 }
};

var tos = Mapper.Map<FromBase[], ToBase[]>( froms );

与:

public class FromBase {
    public int Prop0 { get; set; }
}
public class FromD1 : FromBase {
    public int Prop1 { get; set; }
}
public class FromD2 : FromBase {
    public int Prop2 { get; set; }
}

public class ToBase {
    public int P0 { get; set; }
}
public class ToD1 : ToBase {
    public int P1 { get; set; }
}
public class ToD2 : ToBase {
    public int P2 { get; set; }
}

它看起来像 Automapper 文档上的 示例.

It looks like the example on Automapper's doc.

但是 Mapper.AssertConfigurationIsValid() 断言抛出:

AutoMapperConfigurationException:以下 1 个属性ToBase 未映射:P0添加自定义映射表达式,忽略或重命名属性FromBase."

AutoMapperConfigurationException: "The following 1 properties on ToBase are not mapped: P0 Add a custom mapping expression, ignore, or rename the property on FromBase."

除非我遗漏了什么,与示例的唯一区别是我不依赖约定,使用 ForMember 手动映射属性.还有几个派生类.不知道这些会是什么问题,但我想不出别的.

Unless I am missing something, the only differences with the example it that I am not relying on conventions, mapping the properties manually with ForMember. Also there are several derived classes. Not sure how these would be a problem, but I can't think of anything else.

有什么想法吗?

推荐答案

映射实际上工作正常,虽然配置验证断言失败...

The mapping actually works fine, although the configuration validation assertion fails...

这篇关于如何使用显式成员映射为多态配置 AutoMapper?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)