【发布时间】:2017-06-13 22:57:27
【问题描述】:
我有一个视图模型,例如
public class RootViewModel
{
public CreateCompanyViewModel Company { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
public CreateUserTypeViewModel UserType { get; set; }
}
而CreateCompanyViewModel 和CreateUserTypeViewModel 就像
public class CreateCompanyViewModel
{
public string CompanyName { get; set; }
}
public class CreateUserTypeViewModel
{
public string UserTypeName { get; set; }
}
我希望将此 RootVM 扁平化为多个 DTO。我拥有的上述 RootVM 的 3 个 DTO 就像
public class UserDTO
{
public string Name { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
}
public class CompanyDTO
{
public string CompanyName { get; set; }
}
public class UserTypeDTO
{
public string UserTypeName { get; set; }
}
注意:请注意,CompanyDTO 和 UserTypeDTO 与 RootVM 不同,不是 UserDTO 的嵌套对象(部分)。
当我使用 AutoMapper 进行映射时,RootVM 属性被映射到 UserDTO,但 CompanyDTO 和 UserTypeDTO 如预期的那样为空。
我尝试使用MapFrom 和ResolveUsing 方法使用ForMember 函数映射它们,但它们都显示错误为
成员的自定义配置仅支持顶级 类型上的单个成员。
更新 下面是我的映射代码
CreateMap<RootViewModel, CompanyDTO>();
CreateMap<RootViewModel, UserDTO>();
CreateMap<RootViewModel, UserTypeDTO>();
CreateMap<CreateCompanyViewModel, CompanyDTO>();
CreateMap<CreateUserTypeViewModel, UserTypeDTO>();
我正在使用 AutoMapper 5.2.0
更新 - 修复: 那么我发现,要么我必须手动对所有属性使用 .ForMember,否则要使自动约定起作用,我需要使用 https://github.com/AutoMapper/AutoMapper/wiki/Flattening 或 https://arnabroychowdhurypersonal.wordpress.com/2014/03/08/flattening-object-with-automapper/。
这是使它工作的唯一方法。
希望我能做到.ForMember(d => d, s => s.MapFrom(x => x.Company)),它会映射来自CreateCompanyViewModel => CompanyDTO 的所有属性。这本来会很方便,但 AutoMapper 不支持。
【问题讨论】:
-
您是否分别为公司CompanyDTO和CreateCompanyViewModel添加了映射?
-
我为 RootViewModel => UserDTO, RootViewModel => CompanyDTO, RootViewModel => UserTypeDTO, CreateCompanyViewModel => CompanyDTO, CreateUserTypeViewModel => UserTypeDTO 添加了映射
-
删除 RootViewModel => CompanyDTO 和 RootViewModel => UserTypeDTO 并尝试
-
不,它不起作用,因为我试图从 RootViewModel 获取 CompanyDTO 并删除映射会引发错误,因为 RootViewModel => CompanyDTO 不存在映射配置
-
你能发布你的映射代码吗?
标签: c# automapper