自动映射器模型>视图模型映射异常



我有以下模型和视图模型(为简洁起见进行了编辑):

public class Advert
{
    public virtual long Id { get; set; }
    public virtual string Title { get; set; }
    public virtual string Descrip { get; set; }
    public virtual IList<AdvertImage> AdvertImages { get; set; }
}
public class AdvertImage
{
    public virtual byte DisplayOrder { get; set; }
    public virtual string Filename { get; set; }
    public virtual string UrlDirectoryRoot { get; set; }
    public virtual long FilesizeBytes { get; set; }
    public virtual Advert Advert { get; set; }
}
public class AdvertImageViewModel
{
    public virtual string Filename { get; set; }
    public virtual byte DisplayOrder { get; set; }
}
public class ListAdvertViewModel
{
    public long Id { get; set; }
    public virtual string Title { get; set; }
    public virtual string Descrip { get; set; }
    public AdvertImageViewModel AdvertImage { get; set; }
}

我有以下自动映射器映射:

Mapper.CreateMap<AdvertImage, AdvertImageViewModel>();
Mapper.CreateMap<Advert, ListAdvertViewModel>()
                .ForMember(d => d.AdvertImage, o => o.MapFrom(s => (s.AdvertImages == null ? null : s.AdvertImages.First())));

然后,我的控制器方法之一执行以下操作,以检索广告列表(每个广告可能具有任意数量的广告图像):

var ads = _advertService.GetAdverts();

然后,我尝试将这些广告映射到我的ListAdvertViewModel ViewModel 类中

var mappedAds = Mapper.Map<IList<Advert>, IList<ListAdvertViewModel>>(ads);

但是,如果返回的广告之一(在"ads"变量中)有一些要映射的图像,则这种情况就会消失。我得到的错误是:

[InvalidOperationException: Sequence contains no elements]
   System.Linq.Enumerable.First(IEnumerable`1 source) +498
   AutoMapper.DelegateBasedResolver`2.Resolve(ResolutionResult source) +153
   System.Linq.Enumerable.Aggregate(IEnumerable`1 source, TAccumulate seed, Func`3 func) +160
   AutoMapper.Mappers.PropertyMapMappingStrategy.MapPropertyValue(ResolutionContext context, IMappingEngineRunner mapper, Object mappedObject, PropertyMap propertyMap) +250
[AutoMapperMappingException: 
Mapping types:
Advert -> AdvertImageViewModel
MyProject.Models.Advert -> MyProject.ViewModels.AdvertImageViewModel
Destination path:
IList`1[1].AdvertImage

我不知道为什么这个广告图片映射会导致问题?

首先更改为FirstOrDefault,它应该可以工作。

Mapper.CreateMap<Advert, ListAdvertViewModel>()
            .ForMember(d => d.AdvertImage, o => o.MapFrom(s => (s.AdvertImages == null ? null : s.AdvertImages.FirstOrDefault())));

相关内容

  • 没有找到相关文章

最新更新