[英]Flatten Complex Object To Multiple Flatten Objects Using AutoMapper
我有一個視圖模型,例如
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; }
}
注意:請注意,與UserDTO
不同, CompanyDTO
和UserTypeDTO
不是UserDTO
嵌套對象(一部分)。
當我使用AutoMapper進行映射時, UserDTO
屬性被映射到UserDTO
但是CompanyDTO
和UserTypeDTO
都為空。
我嘗試通過將ForMember
函數與MapFrom
和ResolveUsing
方法一起使用來映射它們,但是它們都顯示錯誤為
類型的頂級單個成員僅支持成員的自定義配置。
更新下面是我的映射代碼
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不支持此功能。
嘗試跟隨
CreateMap<CreateCompanyViewModel, CompanyDTO>();
CreateMap<CreateUserTypeViewModel, UserTypeDTO>();
CreateMap<RootViewModel, CompanyDTO>()
.ForMember(dest => dest.CompanyName, opt => opt.MapFrom(src => src.Company.CompanyName));
CreateMap < RootViewModel, UserTypeDTO()
.ForMember(dest => dest.UserTypeName, opt => opt.MapFrom(src => src.UserType.UserTypeName));
CreateMap<RootViewModel, UserDTO>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.