Make AutoMapper automatically map prefixed properties

你。 提交于 2019-12-10 11:47:20

问题


I want AutoMapper to map automatically Members like this:

class Model { public int ModelId { get; set; } }

class ModelDto { public int Id { get; set; } }

Here, I would do a

CreateMap<Model, ModelDTO>()
    .ForMember(x => x.Id, e => e.MapFrom(x => x.ModelId)

But, how could I make AutoMapper do the mapping automatically? Most of my classes are like that. The Primary key is in the form: ClassName + "Id".

EDIT:

I've tried with this, but it doesn't work:

class Program
{
    static void Main(string[] args)
    {
        Mapper.Initialize(exp =>
        {
            exp.CreateMap<User, UserDto>();
            exp.ForAllPropertyMaps(map => map.DestinationProperty.Name.Equals("Id"), (map, expression) => expression.MapFrom(map.SourceType.Name + "Id"));
        });


        var user = new User() { UserId = 34};
        var dto = Mapper.Map<UserDto>(user);
    }
}

public class UserDto
{
    public int Id { get; set; }
}

class User
{
    public int UserId { get; set; }
}

Thanks!!


回答1:


Yes, the code looks reasonable, but it doesn't work. That's because it runs after the property maps are computed. And there are none in this case, because the names don't match. My bad :) Try

exp.ForAllMaps( (typeMap, mappingExpression) => 
    mappingExpression.ForMember("Id", o=>o.MapFrom(typeMap.SourceType.Name + "Id"))
);


来源:https://stackoverflow.com/questions/47527543/make-automapper-automatically-map-prefixed-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!