<Automapper Model> ViewModel映射异常

时间:2012-06-25 19:10:18

标签: c# .net asp.net-mvc automapper automapper-2

我有以下模型和ViewModel(为简洁起见而编辑):

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())));

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

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

我无法弄清楚为什么这个AdvertImage映射会导致问题?

1 个答案:

答案 0 :(得分:2)

将First改为FirstOrDefault,它应该有效。

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