Andrew
Andrew

Reputation: 933

Automapper: Individual Member Mapping Shared Across Multiple Object Maps?

I have a number of objects that all have a CreatedDt property. Each of these objects needs to be mapped to a matching DTO that has a Created_dt property.

Using AutoMapper, how do I set up a generic configuration to map CreatedDt to Created_dt (and vise versa) without having to do it manually for each map?

Upvotes: 1

Views: 557

Answers (1)

Pawel Maga
Pawel Maga

Reputation: 5787

There is a lot of ways to achieve this result:

Naming conventions, e.g.: this

class Program
{
    static void Main(string[] args)
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<A, ADto>();
            cfg.AddMemberConfiguration()
                .AddName<ReplaceName>(_ => _.AddReplace(nameof(A.CreateDate), nameof(ADto.Created_dt)));
        });

        var mapper = config.CreateMapper();

        var a = new A { CreateDate = DateTime.UtcNow, X = "X" };
        var aDto = mapper.Map<ADto>(a);
    }
}

public class A
{
    public DateTime CreateDate { get; set; }

    public string X { get; set; }
}

public class ADto
{
    public DateTime Created_dt { get; set; }
    public string X { get; set; }
}

Attributes (add this attribute in your base class which has CreatedDt property):

 public class Foo
 {
     [MapTo("Created_dt")]
     public int CreatedDt { get; set; }
 }

Default mapping configuration (AutoMapper Defaults).

Upvotes: 1

Related Questions