如何映射到具有复杂类型参数的目标
本文关键字:复杂 类型参数 目标 何映射 映射 | 更新日期: 2023-09-27 18:04:26
Project
(destination)既有带参数的公共域,也有受保护的无参数域。
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
映射其余源属性?
由于另一个构造函数基于多个源类型,您可能必须显式调用它并通过AutoMapper映射其余属性:
CreateProjectModel project = ...
var model = new Project(project.ProjectName, user);
Mapper.Map(project, model);