Using AutoMapper with F#

前端 未结 2 550
故里飘歌
故里飘歌 2021-02-15 05:18

I\'m trying to use AutoMapper from F#, but I\'m having trouble setting it up due to AutoMapper\'s heavy use of LINQ Expressions.

Specifically, the AutoMapper type

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-15 06:00

    Now that F# is happy to generate a Expression> directly from a fun expression, this is relatively easy to solve. The biggest problem now is that the F# compiler seems to get confused by the overloading of the ForMember method, and is unable to infer correctly what you want. This can be circumvented by defining an extension method with a different name:

    type AutoMapper.IMappingExpression<'TSource, 'TDestination> with
        // The overloads in AutoMapper's ForMember method seem to confuse
        // F#'s type inference, forcing you to supply explicit type annotations
        // for pretty much everything to get it to compile. By simply supplying
        // a different name, 
        member this.ForMemberFs<'TMember>
                (destGetter:Expression>,
                 sourceGetter:Action>) =
            this.ForMember(destGetter, sourceGetter)
    

    You can then use the ForMemberFs method more or less as the original ForMember is intended to work, e.g.:

    this.CreateMap()
        .ForMemberFs
            ((fun d -> d.Slug),
             (fun opts -> opts.MapFrom(fun m -> SlugConverter.TitleToSlug(m.Title)))
    

提交回复
热议问题