Как сделать маппинг через AutoMapper

У меня имеется галерия с фотографиями. Галерия у меня вынесена в отдельную сущность

public class Gallery : Content
{
    private readonly ICollection<Photo> _photos = new HashSet<Photo>();

    public Gallery(string name, string coverUrl)
        : base(name, Categories.Gallery)
    {
        if (string.IsNullOrWhiteSpace(coverUrl))
            throw new ArgumentException("Value cannot be null or whitespace.", nameof(coverUrl));

        CoverUrl = coverUrl;
    }

    public string CoverUrl { get; private set; }

    public IEnumerable<Photo> Photos => _photos.AsQueryable();

    protected internal void AddPhotos(IEnumerable<Photo> photos)
    {
        if (!photos.Any())
            throw new ArgumentException("The image collection is empty", nameof(photos));

        foreach (var photo in photos)
        {
            _photos.Add(photo);
        }
    }
}

Так же имеется Value объект фотография

public class Photo : IValueObjectWithId
{
    private Photo() { }

    protected internal Photo(string photoUrl)
    {
        if (photoUrl == null)
            throw new ArgumentNullException(nameof(photoUrl));

        PhotoUrl = photoUrl;
    }

    public Guid Id { get; private set; }

    public string PhotoUrl { get; private set; }
}

На вход поступает запрос

public record CreatePhotoToGallery(Guid GalleryId, IEnumerable<string> Photos) : IRequest;

Как мне заммапить IEnumerable(string) к IEnumerable(Photo)?

Обработчик добавления фотографий приложил ниже. В нём видно, что метод сервиса как раз принимается IEnumerable(Photo)

public class CreatePhotoToGalleryHandler : IRequestHandler<CreatePhotoToGallery>
{
    private readonly IGalleryService _galleryService;

    private readonly IMapper _mapper;

    public CreatePhotoToGalleryHandler(IGalleryService galleryService, IMapper mapper)
    {
        if (galleryService == null)
            throw new ArgumentNullException(nameof(galleryService));

        if (mapper == null)
            throw new ArgumentNullException(nameof(mapper));

        _galleryService = galleryService;
        _mapper = mapper;
    }

    public async Task<Unit> Handle(CreatePhotoToGallery request, CancellationToken cancellationToken)
    {
        var photos = _mapper.Map<IEnumerable<string>, IEnumerable<Photo>>(request.Photos);

        await _galleryService.AddPhotoAsync(request.GalleryId, photos);

        return Unit.Value;
    }
}

Маппинг, который я сделал не работает)

public class GalleryProfile : Profile
{
    public GalleryProfile()
    {
        CreateMap<CreatePhotoToGallery, Photo>()
            .ForMember(dest => dest.PhotoUrl, opt => opt.MapFrom(x => x.Photos));
    }
}

Ответы (1 шт):

Автор решения: pled

Мне подсказали, что маппить string с Photo это такое себе занятие и тут до меня дошло сделать следующим образом.

Сначала давайте разберёмся с входящим запросом. У нас есть некоторая входящая фотография создадим её тип.

    public record InputPhoto(string PhotoUrl);

Далее в нашем запросе создадим поле, которое принимает IEnumerable<InputPhoto>.

У нас получается следующий входящий запрос:

    public record CreatePhotoToGallery(Guid GalleryId, IEnumerable<InputPhoto> Photos) : IRequest;

Сделаем маппинг

public class GalleryProfile : Profile
{
    public GalleryProfile()
    {
        CreateMap<InputPhoto, Photo>();
    }
}


    public async Task<Unit> Handle(CreatePhotoToGallery request, CancellationToken cancellationToken)
    {
        var photos = _mapper.Map<IEnumerable<InputPhoto>, IEnumerable<Photo>>(request.Photos);

        await _galleryService.AddPhotoAsync(request.GalleryId, photos);

        return Unit.Value;
    }
→ Ссылка