SuperJMN
SuperJMN

Reputation: 13972

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; }
}

Upvotes: 0

Views: 1100

Answers (1)

Lucian Bargaoanu
Lucian Bargaoanu

Reputation: 3516

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

Upvotes: 6

Related Questions