Make AutoMapper automatically map prefixed properties

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!!


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"))
);
链接地址: http://www.djcxy.com/p/37398.html

上一篇: 具体对象到数组

下一篇: 使AutoMapper自动映射前缀属性