我有以下模型和视图模型(为简洁而编辑):
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; }
}
我有以下 AutoMapper 映射:
Mapper.CreateMap<AdvertImage, AdvertImageViewModel>();
Mapper.CreateMap<Advert, ListAdvertViewModel>()
.ForMember(d => d.AdvertImage, o => o.MapFrom(s => (s.AdvertImages == null ? null : s.AdvertImages.First())));
然后我的控制器方法之一执行以下操作,以检索 Adverts 列表(其中每个 Advert 可能具有任意数量的 AdvertImages):
var ads = _advertService.GetAdverts();
然后我尝试将这些广告映射到我的ListAdvertViewModel
ViewModel 类中
var mappedAds = Mapper.Map<IList<Advert>, IList<ListAdvertViewModel>>(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
我不明白为什么这个 AdvertImage 映射会导致问题?