1
votes

I am trying to perform the following Automapper mapping for an OrderBy:

Expression<Func<ServerObject, object>> serverQueryable = x => x.TestEnumKVP.Value;
Mapper.Map<Expression<Func<ServerObject, object>>, Expression<Func<DatabaseObject, object>>(serverQueryable)

I want to map the ServerObject expression to a DatabaseObject expression

ServerObject defined as:

public class ServerObject
{
    public KeyValuePairEx TestEnumKVP { get; set; }
}

KeyValuePairEx is a wrapper for the Enumeration which stores the Int16 value and the string value:

public enum TestEnum : Int16 { Test1, Test2, Test3 }

public class KeyValuePairEx
{
    internal KeyValuePairEx(TestEnum key, string value) { }

    public TestEnum Key { get; set; }
    public string Value { get; set; }
}

DatabaseObject defined as:

public class DatabaseObject
{
    public string TestEnumId { get; set; }
}

The Mapping I have is:

AutoMapper.Mapper.Initialize(config =>
{
    config.CreateMap<DatabaseObject, ServerObject>().ForMember(dest => dest.TestEnumKVP.Value, opt => opt.MapFrom(src => src.TestEnumId));
});

The mapping fails with:

'Expression 'dest => dest.TestEnumKVP.Value' must resolve to top-level member and not any child object's properties. Use a custom resolver on the child type or the AfterMap option instead.'

I need ServerObject.TestEnumKVP.Value to Map to DatabaseObject.TestEnumId. I am aware that Expression mappings are reversed - hence why the Map is from DatabaseObject to ServerObject. I have spent many hours on this and am at a loss as to how to get the mapping to work!

NB. I am using AutoMapper 6.1.1

Any help would be appreciated!

2

2 Answers

2
votes

Thank you Lucian, I followed the github link and the solution offered by Blaise has worked. See below:

CreateMap<DatabaseObject, ServerObject>().ForMember(dest => dest.TestEnumKVP, opt => opt.MapFrom(src => src));
CreateMap<DatabaseObject, KeyValuePairEx>().ForMember(dest => dest.Value, opt => opt.MapFrom(src => src.TestEnumId));

I was starting to look for at workarounds so delighted it was possible and that the solution was so clean and concise.

Thanks again!

0
votes

The error and the solution are right there in the message. Forget about all the expression stuff. The ForMember is broken. Try ForPath instead. Expression mapping now supports ForPath. See https://github.com/AutoMapper/AutoMapper/issues/2293.