Make AutoMapper automatically map prefixed propert

2019-06-08 19:38发布

问题:

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"))
);


标签: c# AutoMapper