Automapper: A lambda expression with a statement body cannot be converted to an expression tree

Created on 13 Jul 2012  路  7Comments  路  Source: AutoMapper/AutoMapper

Tried to upgrade to version 2.0 and found this "A lambda expression with a statement body cannot be converted to an expression tree". I have a ton of mappings, some of which are complex enough to warrant a statement body. Is there a way to make this version backward compatible? Is there a trick that could help ease the pain of upgrading these mappings?

Most helpful comment

Yes - just replace these with ResolveUsing. MapFrom has some extra stuff that needs expression trees (like null checking etc).

All 7 comments

Yes - just replace these with ResolveUsing. MapFrom has some extra stuff that needs expression trees (like null checking etc).

Just for future reference, when using ResolveUsing with a lambda expression with a statement body, intellisense can't differentiate between the overloads Func<T, object> resolver and Func<ResolutionResult, object> resolver. You'll get an error until you reference a property of T (without using intellisense).

Mapper.CreateMap<Header, HeaderDto>()
    .ForMember(dest => dest.Note, opt => opt.ResolveUsing(src =>
    {
        return ""; // src appears to be a ResolutionResult object!
    }));

The call is ambiguous between the following methods or properties: 'IMemberConfigurationExpression<Header>.ResolveUsing(System.Func<Header,object>)' and 'IMemberConfigurationExpression<Header>.ResolveUsing(System.Func<ResolutionResult,object>)'

By referencing src.Note (a property of the Header object), everything works:

Mapper.CreateMap<Header, HeaderDto>()
    .ForMember(dest => dest.Note, opt => opt.ResolveUsing(src =>
    {
        return src.Note; // src is now a Header object!
    }));

AutoMapper 3.2.1, Visual Studio 2012, DotNet 4.5

Of course, even if you don't reference a property of T in the lambda expression statement body, you can explicitly indicate the Func type you want.

So this works:

Mapper.CreateMap<Header, HeaderDto>()
    .ForMember(dest => dest.Note, opt => opt.ResolveUsing((Header src) =>
    {
        return ""; // src is a Header object
    }));

You don't know how this post saved me... Thanks!!!!!

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JobaDiniz picture JobaDiniz  路  5Comments

jbogard picture jbogard  路  7Comments

fruitbatinshades picture fruitbatinshades  路  3Comments

brendonwm picture brendonwm  路  7Comments

gmarokov picture gmarokov  路  6Comments