0

I have classes EntityA to DtoA and 2 usages of automapper in my .NET project.

First one is:

var result1 = dbContext
    .Set<EntityA>()
    .Where(...)
    .ProjectTo<DtoA>(new { param1 = true } )
    .ToList();

And the second:

var aList = dbContext
    .Set<EntityA>()
    .Where(...)
    .ToList();

var result = Mapper
    .Map<DtoA[]>(aList, options => options.Items["param1"] = true);

I want to have a reusable mapping working for both cases. This mapping has to be conditional for some fields based on param1 value. How to implement it within single CreateMap<,>().ForMember() API ?

Andrey Pesoshin
  • 1,136
  • 1
  • 14
  • 30

1 Answers1

0

I didn't exactly get the logic you want, but you could put any logic into a method like this:

 c.CreateMap<A, B>()
    .ForMember(dest => dest.Items, opt => opt.ResolveUsing(src =>
    {
       if (src.Items["param1"] == true)
       {
           // Do whatever
       }

       return /*do whatever else*/;
    }));

Is that what you want or did I misunderstand the question?

Edit: I'll give it another try:

var result1 = dbContext
    .Set<EntityA>()
    .Where(...)
    .Select(c => mapper.Map<A>(c))
    .ToList();

However still not understanding completely what you want. Can you give an example with data, like which set should be converted into which?

Maxim Zabolotskikh
  • 3,091
  • 20
  • 21
  • yeah, you got the idea. But the pitfall here is that opt.ResolveUsing does not work for .ProjectTo<>() API. The documentation offers to use *parameterization* approach with .MapFrom API http://docs.automapper.org/en/stable/Queryable-Extensions.html#parameterization here. The question is how to make both parameterization approaches work withing single mapping ? Or, maybe, how to split support both .MapFrom and .ProjectTo for EntityA->DtoA in a single application ? – Andrey Pesoshin Oct 18 '18 at 07:39