如何使用 Automapper 将值分配给目标模型中而非源模型中的字段?

How can I use Automapper to assign values to fields in destination model but not in source model?

我正在 ASP.NET MVC 5 应用程序中掌握 Automapper 的窍门,目的是将域模型映射到 ViewModel。有一种情况我仍然不知道如何解决:当 ViewModel(目标)有一个 属性 不在域模型(源)中时。

ViewModel 中的两个附加属性是我需要在控制器中填充的 IEnumerable。

正如我在 Controller 块(如下所示)的注释中所解释的那样,域模型是源并将被馈送到视图 table。 ViewModel 中的额外两个 IEnumerable 将填充 HTML.BeginForm() 块中的 DropDownLists。

我看到的示例使用 .CreateMap<>().ForMember() 处理源模型中属性的计算或转换,而不是这种情况,我在控制器中根据 Action 参数定义一些东西。

我的问题是如何映射控制器中定义的其余 IEnumerables?

App_Start

中的映射配置
public static class MappingConfig
{
    public static void RegisterMaps()
    {
        AutoMapper.Mapper.Initialize(config =>
            {
                config.CreateMap<StudentRoster, StudentRosterViewModel>();
            });
    }
}

模型和视图模型:

[Table("StudentRoster")]
public partial class StudentRoster
{
    public int ID { get; set; }

    [Required]
    [StringLength(3)]
    public string Campus { get; set; }

    [Required]
    [StringLength(4)]
    public string FiscalYear { get; set; }

    [Required]
    [StringLength(50)]
    public string StudentName { get; set; }

    public int StudentID { get; set; }               

}

// ViewModel

public partial class StudentRosterViewModel
{
    // Automapper successfully mappped the first five fields
    // to the parent class
    public int ID { get; set; }

    public string Campus { get; set; }

    public string FiscalYear { get; set; }

    public string StudentName { get; set; }

    public int StudentID { get; set; }     


    // These two fields are not in the parent class
    public IEnumerable<SelectListItem> CampusListSelect { get; set; }
    public IEnumerable<SelectListItem> FiscalYearSelect { get; set; }
}

控制器中的索引操作:

// GET: StudentRosterViewModels
public ActionResult Index(string campus = "MRA", string fy="FY16")
{
    IEnumerable<StudentRoster> query = db.StudentRosters.Where(m=>m.Campus==campus).ToList();

    // This successfully maps the domain model to the viewmodel
    // This IEnumerable will display in the "Table"
    IEnumerable<StudentRosterViewModel> mappedQuery =
        AutoMapper.Mapper.Map<IEnumerable<StudentRoster>, IEnumerable<StudentRosterViewModel>>(query);

    // The two remaining IEnumerables need to be mapped to 'mappedQuery'
    //   CampusListSelect and FiscalYearSelect
    // These two IEnumerables will populate the dropdownlists in Html.BeginForm()
    IEnumerable<SelectListItem> CampusList = new SelectList(new List<string> { "CRA", "DRA", "MRA", "PRA" }, campus);
    IEnumerable<SelectListItem> FiscalYearList = new SelectList(new List<string> { "FY12", "FY13", "FY14", "FY15", "FY16" }, fy);                

    return View(mappedQuery.ToList());
}

您可以尝试使用 DynamicMap 来填充您的项目,而无需为映射创建额外的 类。

如果您使用的是旧版本 AutoMapper(4.1 或更低版本),您可以尝试以下操作:

// GET: StudentRosterViewModels
public ActionResult Index(string campus = "MRA", string fy="FY16")
{
    IEnumerable<StudentRoster> query = db.StudentRosters.Where(m=>m.Campus==campus).ToList();

    // This successfully maps the domain model to the viewmodel
    // This IEnumerable will display in the "Table"
    IEnumerable<StudentRosterViewModel> mappedQuery =
        AutoMapper.Mapper.Map<IEnumerable<StudentRoster>, IEnumerable<StudentRosterViewModel>>(query);

    // The two remaining IEnumerables need to be mapped to 'mappedQuery'
    //   CampusListSelect and FiscalYearSelect
    // These two IEnumerables will populate the dropdownlists in Html.BeginForm()
    IEnumerable<SelectListItem> CampusList = new SelectList(new List<string> { "CRA", "DRA", "MRA", "PRA" }, campus);
    IEnumerable<SelectListItem> FiscalYearList = new SelectList(new List<string> { "FY12", "FY13", "FY14", "FY15", "FY16" }, fy);                

    var objForDynamicMapping = new 
    { 
        CampusListSelect = CampusList,
        FiscalYearListSelect = FiscalYearList
    };

    foreach(var mappedItem in mappedQuery)
    {
        // will create the mapping configuration dynamically
        AutoMapper.Mapper.DynamicMap(objForDynamicMapping, mappedItem);
    }

    return View(mappedQuery.ToList());
}

如果您使用的是 AutoMapper 4.2 或更高版本。

那么你只需要把这一行:

var config = new MapperConfiguration(cfg => cfg.CreateMissingTypeMaps = true);

在您创建映射器配置的地方,然后只需使用方法 Map,例如:

mapper.Map(objForDynamicMapping, mappedItem);

而不是 DynamicMap

希望对您有所帮助。