AutoMapper不会将ViewModel映射到Model

时间:2014-01-17 17:46:15

标签: c# model-view-controller model viewmodel automapper

我有ViewModel:

public class EmployeeViewModel
    {
        public Developer Developer { get; set; }
        public Administrator Administrator { get; set; }
    }

和型号:

public class Developer 
        {
            //some stuff
        }

我正在尝试将其映射到Action:

public ActionResult AddDeveloper(EmployeeViewModel employee)
        {
            AutoMapper.Mapper.CreateMap<EmployeeViewModel, Developer>();
            Developer developer = AutoMapper.Mapper.Map<EmployeeViewModel, Developer>(employee);
            .......
        }

之后developer变量没有employee具有的参数值。你能帮我吗?

1 个答案:

答案 0 :(得分:0)

您只是想有效地将​​类映射到属性。您需要明确告诉如何将两个元素放在同一级别上,例如:

public ActionResult AddDeveloper(EmployeeViewModel employee)
        {
            AutoMapper.Mapper.CreateMap<EmployeeViewModel, Developer>()
                      .ForMember(destination => destination, option => option.MapFrom(source => source.Developer));
            Developer developer = AutoMapper.Mapper.Map<EmployeeViewModel, Developer>(employee);
        }

现在同样的事情应该有效。我从未尝试在该级别进行映射,我怀疑您可能必须尝试使用​​“AfterMap”函数,如:https://stackoverflow.com/a/4750709/3002953