自动映射器映射问题

Automapper mapping issue

我需要使用 AutoMapper 将模型映射到视图模型。

型号:

[Table("News")]
public class News
{
    [Key]
    public int Id { get; set; }
    public string Title { get; set; }
    public DateTime DatePostedOn { get; set; }
    public int Position { get; set; }
    public Category Category { get; set; }
    public virtual ICollection<Picture> Pictures { get; set; }
}

[Table("Pictures")]
public class Picture
{
    [Key]
    public int Id { get; set; }
    public DateTime DateCreated { get; set; }
    public string Filename { get; set; }
    public int Type { get; set; }
    public virtual ICollection<News> News { get; set; }
}

视图模型:

public class HomeViewModels
{
    public IList<HomeMainNews> MainNews { get; private set; }
}

public class HomeMainNews
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Date { get; set; }
    public string PictureURL { get; set; }
}

映射:

Mapper.CreateMap<News, HomeMainNews>();

如何根据特定条件将具有一组图片的新闻映射到只有一张图片的视图模型"Type = 2"

当前解决方案:

    vm.MainNews = db.News
              .Select(n => new HomeMainNews { 
                                Id = n.Id,
                                Date = n.DatePostedOn.ToString(),
                                Title = n.Title,
                                PictureURL = n.Pictures.Where(p => p.Type == 1).Select(p => p.Filename).FirstOrDefault().ToString()
                        }).ToList();

Automapper 解决方案:

    vm.MainNews = db.News.Project().To<HomeMainNews>().ToList();

试试这个

Mapper.CreateMap<News, HomeMainNews>()
            .ForMember(mainNew => mainNew.Date, opt => opt.MapFrom(news => news.DatePostedOn))
            .ForMember(mainNew => mainNew.PictureURL, opt => opt.MapFrom(news => news.Pictures.First(pic => pic.Type == 2).Filename));