如何映射到具有复杂类型ctor参数的目标?

时间:2014-05-21 08:02:28

标签: c# automapper

Project(目的地)既有公共ctor,也有参数和受保护的无参数ctor。

public Project(String name, User initiator) {
    this.Name = name;
    this.Initiator = initiator;
    this.InitializedOn = DateTime.Now;
}

// meant only to support some EF-related operations
protected Project() {}

地图:

Mapper.CreateMap<CreateProjectModel, Project>().ForMember(
    dest => dest.Name,
    opt => opt.MapFrom(src => src.ProjectName)
);

考虑create行动的摘录:

var user = dbContext.Users.Find(someId);
// initialize model using protected ctor - that's the behavior by default
var model = Mapper.Map<Project>(project);    
// then initialize some additional properties

// or initialize model as it needs to be
// var model = new Project(project.ProjectName, user); 
// and populate everything by hand

是否可以使用new Project(project.ProjectName, user)初始化并使用Automapper映射其余的源属性?

1 个答案:

答案 0 :(得分:1)

由于其他构造函数基于多种源类型,您可能必须显式调用它并通过AutoMapper映射其余的属性:

CreateProjectModel project = ...

var model = new Project(project.ProjectName, user);
Mapper.Map(project, model);