6
我創建了一個ListTypeConverter:如何使用AutoMapper將具有多個通用列表的對象映射到具有相應非通用列表的另一個對象?
type ListTypeConverter<'source, 'destination>() =
interface ITypeConverter<'source list, Proxies.List> with
member this.Convert(source, destination, context) =
let proxyList = new Proxies.List()
source
|> List.map(fun item -> _mapper.Map<'source, 'destination>(item))
|> List.iter(fun item -> proxyList.addEnd(item) |> ignore)
proxyList
與用法:ForMemberFs by Ian Griffiths
this.CreateMap<SourceItemType list, Proxies.List>().ConvertUsing<ListTypeConverter<SourceItemType, DestItemType>>()
this.CreateMap<SourceType, DestType>().
ForMemberFs((fun d -> d.MyNonGenericList), (fun opts -> opts.MapFrom(fun s -> s.MyGenericList))).
這工作得很好,如果我只對我說從'a list -> Proxy.List
映射主地圖一個屬性。但是現在我介紹'b -> Proxy.List
的第二個映射,然後我得到一個InvalidCastException。
引入第二映射導致異常:
this.CreateMap<SourceItemType list, Proxies.List>().ConvertUsing<ListTypeConverter<SourceItemType, DestItemType>>()
this.CreateMap<SourceItemType2 list, Proxies.List>().ConvertUsing<ListTypeConverter<SourceItemType2, DestItemType2>>()
this.CreateMap<SourceType, DestType>().
ForMemberFs((fun d -> d.MyNonGenericList), (fun opts -> opts.MapFrom(fun s -> s.MyGenericList))).
ForMemberFs((fun d -> d.MyNonGenericList2), (fun opts -> opts.MapFrom(fun s -> s.MyGenericList2))).
例外:
Unable to cast object of type 'obj' to type 'DestItemType'