Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If else in AutoMapper ForMember

Tags:

c#

automapper

I am trying to map two different objects

CreateMap<A, B>()
  .ForMember(x => x.Quantity, y => y.MapFrom(z =>z.QuantityList.First().TotalQuantity))

I would like to assign x.Quantity = 1 if z =>z.QuantityList.First().TotalQuantity == 0 othwerwise the above mapping.

How is this done in ForMember()?

like image 838
blue piranha Avatar asked Dec 10 '22 10:12

blue piranha


1 Answers

There are a couple of options. You could wrap the if/else in a function, you can use an if {} block, but in this case the easiest way might be to use an inline ternary operator:

E.G:

.ForMember(dest => dest.Quantity, opt => opt
    .MapFrom(src => (src.Quantitylist.First().TotalQuantity == 0) ? 1 
    : src.QuantityList.First().TotalQuantity))
like image 103
istrupin Avatar answered Dec 26 '22 14:12

istrupin