使用automapper将多种类型映射到一种类型

时间:2012-08-26 19:39:28

标签: c# automapper

IEnumerable<ReleaseViewModel> releaseViewModels = Mapper.Map<IEnumerable<Release>, IEnumerable<ReleaseViewModel>>(releases);
IEnumerable<TemplateViewModel> templateViewModels = Mapper.Map<IEnumerable<Template>, IEnumerable<TemplateViewModel>>(templates); 

CreateTestplanViewModel viewModel = new CreateTestplanViewModel { Releases = releaseViewModels, Templates = templateViewModels };


public class CreateTestplanViewModel
{
    public CreateTestplanViewModel() { }
    public CreateTestplanViewModel(IEnumerable<Template> templates, IEnumerable<Release> releases)
    {
        Templates = templates.Select(t => new TemplateViewModel { TemplateId = t.TemplateId, Name = t.Name });
        Releases = releases.Select(t => new ReleaseViewModel { ReleaseId = t.ReleaseId, Name = t.Name });
        CreatedBy = WindowsIdentity.GetCurrent().Name;
        CreatedAt = DateTime.Now; //.Date.ToShortDateString();
    }

    [Required(ErrorMessage = "No Template selected.")]
    public int? SelectedTemplateId { get; set; }
    public IEnumerable<TemplateViewModel> Templates { get; set; }

    [Required(ErrorMessage = "No Release selected.")]
    public int? SelectedReleaseId { get; set; }
    public IEnumerable<ReleaseViewModel> Releases { get; set; }

    [HiddenInput(DisplayValue = false)]
    public int Id { get; set; }

    [Display(Name="Testplan name")]
    public string Name { get; set; }

    public string CreatedBy { get; set; }     
    public DateTime CreatedAt { get; set; }        
}

目前,我将IEnumerable<TestplanViewModel> AND IEnumerable<ReleaseViewModel>手动映射到CreateTestplanViewModel对象,方法是将它们传递给构造函数,然后在内部执行linq select。

如何使用AutoMapper为我的CreateTestplanViewModel创建多个IEnumerable类型的映射?

0 个答案:

没有答案