public class SecurityAccess : IdentityUser {
public string LName { get; set; }
public string FName { get; set; }
public string MName { get; set; }
public DateTime NameDate { get; set; }
public DateTime DOB { get; set; }
public string Spouse { get; set; }
public string Comments { get; set; }
public Address Address { get; set; }
}
public class Address {
public int Id { get; set; }
public int OwnerId { get; set; }
public DateTime CreationDate { get; set; }
public Company Company { get; set; }
public string Department { get; set; }
public string Title { get; set; }
public string Location{ get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
public string Salutation { get; set; }
public bool Active { get; set; }
}
public class Company {
public int Id { get; set; }
public string Name { get; set; }
public DateTime CompanyDate { get; set; }
}
public class ContactRegisterViewModel {
public byte Id { get; set; }
public String FName { get; set; }
public String LName { get; set; }
public String CompanyName { get; set; }
public String AddressesTitle { get; set; }
public String AddressesLocation { get; set; }
public String AddressesCity { get; set; }
public String AddressesState { get; set; }
public String AddressesZip { get; set; }
public String AddressesCountry { get; set; }
public String AddressesPhone { get; set; }
public String AddressesEmail { get; set; }
}
我在Automapper中设置了以下映射
CreateMap<ContactRegisterViewModel, SecurityAccess>()
.ForMember(dest => dest.Address,
opts => opts.MapFrom(
src => new Address
{
Address1 = src.AddressesAddress1,
Title = src.AddressesTitle,
City = src.AddressesCity,
State = src.AddressesState,
Zip = src.AddressesState,
Country = src.AddressesCountry,
Email = src.AddressesEmail,
Phone = src.AddressesPhone,
})).ReverseMap();
我正在尝试将ContactRegisterViewModel转换为SecurityAccess。转换部分有效。我能够在SecurityAccess中获取相关属性,包括SecurityAccess模型中的Address属性字段,但是我试图进一步将ContactRegisterViewModel属性CompanyName映射到Address.Company.Name中的属性。
我可以如何映射整个对象树?
答案 0 :(得分:1)
因此,一个可能的解决方案将是这样的:
CreateMap<ContactRegisterViewModel, SecurityAccess>()
.ForMember(d => d.Address, o => o.MapFrom(s => s));
CreateMap<ContactRegisterViewModel, Address>()
.ForMember(d => d.Title, o => o.MapFrom(s => s.AddressesTitle))
.ForMember(d => d.Company, o => o.MapFrom(s => s));
CreateMap<ContactRegisterViewModel, Company>()
.ForMember(d => d.Name, o => o.MapFrom(s => s.CompanyName));
这应该可以完成工作,虽然它可能不是最优雅的。可能值得一试这些ConstructUsing
/ ConvertUsing
方法(参见here)。