当前,我们使用扩展方法来提供此功能,但我不禁感到有一个更干净的解决方案。我玩过AutoMapper,但在复杂情况下无法完全解决它的问题。对于简单的1:1,它可以工作,但是如果需要对数据进行任何摆弄-这似乎令人失望。所以,我有类似的东西:public static class ProvisioningExtensions{ // Convert ProvisioningServicesProxy.Provisioning to ProvisioningDetailsModel. public static ProvisioningDetailsModel ToProvisioningDetailsModel(this Provisioning provisioning) { var provisioningDetailsModel = new ProvisioningDetailsModel { ID = provisioning.ID, TaskDeviceID = provisioning.TaskDevice.ID, ServiceGroupID = provisioning.ServiceGroup.ID, ServiceID = provisioning.Service.ID, PatchSchedules = provisioning.PatchSchedules.Select(ps => ps.ToPatchScheduleDetailsModel()).ToList() }; return provisioningDetailsModel; } // Convert ProvisioningDetailsModel to ProvisioningServicesProxy.PatchSchedule. public static Provisioning ToProvisioning(this ProvisioningDetailsModel provisioningDetailsModel) { WorkflowManager workflowManager = new WorkflowManager(); ProvisioningManager provisioningManager = new ProvisioningManager(); TaskDevice taskDevice = workflowManager.GetTaskDeviceByID(provisioningDetailsModel.TaskDeviceID); Service service = provisioningManager.GetServiceByID(provisioningDetailsModel.ServiceID); ServiceGroup serviceGroup = provisioningManager.GetServiceGroupByID(provisioningDetailsModel.ServiceGroupID); var provisioning = new Provisioning { ID = provisioningDetailsModel.ID, TaskDevice = taskDevice, ServiceGroup = serviceGroup, Service = service, PatchSchedules = provisioningDetailsModel.PatchSchedules.Select(ps => ps.ToPatchSchedule()).ToArray() }; return provisioning; }}ProvisioningDetailsModel是一个仅包含模型属性的类。没什么特别的。我曾考虑过装饰Provisioning域对象,以使其可以代替模型使用,但是我决定反对。如果我想以两种不同的方式表示Provisioning数据怎么办-如果我将域对象本身用作模型,那将是不可能的。我应该考虑其他哪些选择?扩展方法将是我的最后选择-尤其是当我必须在ToProvisioning内部进行相对繁重的工作时。 最佳答案 在AutoMapper中,您可以创建类型自定义转换器。这是通过实现ITypeConverter 接口来完成的。 public class CreateMomentoCommandToMomentoConverter : ITypeConverter<CreateMomentoCommand, Momento> { public Momento Convert(ResolutionContext context) { var source = (CreateMomentoCommand) context.SourceValue; var momento = new Momento {Username = source.Username}; return momento; } }使用AutoMapper初始化客户类型转换器 /// <summary> /// Configures the aut do mapper. /// </summary> public static void ConfigureAutoMapper() { AutoMapper.Mapper.Initialize(c=> c.CreateMap<CreateMomentoCommand, Momento>().ConvertUsing(new CreateMomentoCommandToMomentoConverter())); }最后映射它。Mapper.Map<CreateMomentoCommand, Momento>(command); 10-04 12:31