开发者

How to Perform String Lookups in Automapper Based on Destination Property Name?

开发者 https://www.devze.com 2023-01-11 01:21 出处:网络
I\'d like to generalize a property lookup from code like this .ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.GetValue(\"FirstName\"))

I'd like to generalize a property lookup from code like this

.ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.GetValue("FirstName"))
.ForMember(dest => dest.LastName, opt => opt.MapFrom(src => src.GetValue("LastName"))
... (repeated for many propertie开发者_开发问答s)

to a one-liner, conceptually something like this:

// How can I access the property name?
.ForAllMembers(opt => opt.MapFrom(src => src.GetValue([[PROPERTYNAME]]))   

The "source" value is almost always be a string-based lookup into a GetValue() method, using the property name from the destination. I just don't know how to access the string name of the property from the "source" lambda when it's defined in the "destination" lambda. It seems like there ought to be a way to do this but I'm not having luck finding a relevant example.

I hope this makes sense. Thanks in advance for any insights,

Jeff


You should be able to use a Custom Resolver that uses reflection to get all the property names and then calls your GetValue() method of the source object.


I know this question is like 2-3 years old, but I ran into something like this and it was very hard to find the answer, mostly because IValueResolver interface is not documented in the documentation.

I ended up doing something like this:

public class UserProfileMapping : Profile
{
    protected override void Configure()
    {
        Mapper.CreateMap<ProfileBase, UserProfileModel>()
              .ForAllMembers(m => m.ResolveUsing<ProfileValueResolver>());
    }

    public class ProfileValueResolver : IValueResolver
    {
        public ResolutionResult Resolve(ResolutionResult source)
        {
            return source.New(
                ((ProfileBase)source.Value)
                .GetPropertyValue(source.Context.MemberName)
            );
        }
    }
}

Hope this helps someone.

0

精彩评论

暂无评论...
验证码 换一张
取 消