0

I have a below MappingProfile. It is working fine. But do you know how to write it in a single line or a more concise manner?

public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            CreateMap<ExpenseDto, Expense>().ForMember(expense => expense.Image,
            opt => opt.MapFrom(expenseDto => Convert.FromBase64String(expenseDto.Image)));

            CreateMap<Expense, ExpenseDto>().ForMember(expenseDto => expenseDto.Image,
           opt => opt.MapFrom(expense => Convert.ToBase64String(expense.Image)));
   
        }
    }

Expense Entity

public class Expense
    {
       public byte[]? Image { get; set; }
    }

Expense Dto

public record ExpenseDto
{
   public string? Image { get; init; }
}
Sampath
  • 63,341
  • 64
  • 307
  • 441
  • I think that can be impossible because how Automapper will know when to convert string to string and when string to base64... – kalit Apr 11 '22 at 07:07
  • This isn't a mapping. This is serialization from binary to string with a specific encoding. AutoMapper was built to handle straightforward mappings, not act as a transformation library. Check [Automapper's Design Philosophy](https://jimmybogard.com/automappers-design-philosophy/). Besides, what you want to do is what a JSON serializer would do with a DTO *after* it was transformed by Automapper. Why is Automapper to do this? – Panagiotis Kanavos Apr 11 '22 at 07:08
  • @PanagiotisKanavos `Why is Automapper to do this?` It would be great if you'll show me how to do this without Automapper? I have put my `entity` and `dto` for your reference. If you'll need any other info please let me know. – Sampath Apr 11 '22 at 07:13
  • 1
    You can specify [a custom converter](https://docs.automapper.org/en/stable/Custom-type-converters.html) from `byte[]` to `string` and use it for such fields. What I asked though is why *your code* is doing this instead of letting the serializer do it. BASE64 is used when making or returning HTTP results, or serializing to files. It's not needed in databases – Panagiotis Kanavos Apr 11 '22 at 07:19
  • 1
    You can create a custom type converter from `byte[]` to `string` and vice versa. And then you can remove those resolvers. – Lucian Bargaoanu Apr 11 '22 at 07:20
  • 1
    This conversion will cause performance issues, especially under load. Performing the conversion like this allocates a big string that needs to be garbage-collected. The serializer on the other hand would right the converted characters directly to the output stream. – Panagiotis Kanavos Apr 11 '22 at 07:24
  • @PanagiotisKanavos Ok sure. I'll see your link and try that. If I'll have any issues I'll create a new question for that. Thanks! – Sampath Apr 11 '22 at 07:30

0 Answers0