简体   繁体   English

具有不同源类型的 Automapper 条件映射

[英]Automapper conditional mapping with different source types

I'm attempting to map to a custom type property in a DTO from one of a few different navigation properties of a source entity, conditional on which of them is not null.我试图从源实体的几个不同导航属性之一映射到 DTO 中的自定义类型属性,条件是它们中的哪个不为空。

Simplified version (some of the conditional maps removed):简化版(删除了一些条件映射):

 CreateMap<MyDTO, MyEntity>()
                  .ForMember(dest => dest.Order,
                  opt =>
                  {
                  opt.MapFrom(src => src.OrderType1 != null ? src.OrderType1 :
                  src.OrderTypeA.OrderType1 != null ? OrderTypeA.OrderType1 :
                  src.OrderType2 != null ? src.OrderType2 : null
                  ));

It won't compile because OrderType2 entity is of a different type then OrderType1它不会编译,因为 OrderType2 实体的类型与 OrderType1 不同

Type of conditional expression cannot be determined because there is no implicit conversion between 'OrderType1' and 'OrderType2'无法确定条件表达式的类型,因为“OrderType1”和“OrderType2”之间没有隐式转换

I've tried creating an empty type, having both entity types inherit from this then casting to the base type in the conditional expression.我尝试创建一个空类型,让两种实体类型都继承自 this,然后在条件表达式中转换为基本类型。 This throws an exception because it has unmapped types for all properties.这将引发异常,因为它具有所有属性的未映射类型。

Assume I could refactor to use the base class on navigation properties throughout and create a mapping from base to derived for each entity to get this to work but feel it would introduce too many changes.假设我可以重构以在整个导航属性上使用基类,并为每个实体创建从基类到派生类的映射,以使其正常工作,但感觉它会引入太多更改。

Is there an alternative approach to this using Automapper, or another way to resolve the issue - have multiple conditions that can return different source types to be mapped?是否有使用 Automapper 的替代方法,或另一种解决问题的方法 - 有多个条件可以返回要映射的不同源类型?

It seems too simple but got it working by casting to object within the conditional:看起来太简单了,但是通过在条件中强制转换为对象来使其工作:

 CreateMap<MyDTO, MyEntity>()
                  .ForMember(dest => dest.Order,
                  opt =>
                  {
                  opt.MapFrom(src => src.OrderType1 != null ? src.OrderType1 :
                  src.OrderTypeA.OrderType1 != null ? OrderTypeA.OrderType1 :
                  src.OrderType2 != null ? (object)src.OrderType2 : null
                  ));

This runs and creates all the required maps.这会运行并创建所有必需的地图。

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

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