有没有一种方法可以使automapper映射以下内容而不必映射每个属性或为每个地址创建不同的视图模型?
来源:
public class ViewModel
{
public decimal? BillingAddressLatitude { get; set; }
public string BillingAddressLine1 { get; set; }
public string BillingAddressLine2 { get; set; }
public string BillingAddressLine3 { get; set; }
public decimal? BillingAddressLongitude { get; set; }
public string BillingAddressPostalCode { get; set; }
public string BillingAddressUnit { get; set; }
public long? MailingAddressCityId { get; set; }
public decimal? MailingAddressLatitude { get; set; }
public string MailingAddressLine1 { get; set; }
public string MailingAddressLine2 { get; set; }
public string MailingAddressLine3 { get; set; }
public decimal? MailingAddressLongitude { get; set; }
public string MailingAddressPostalCode { get; set; }
public string MailingAddressUnit { get; set; }
public string Name { get; set; }
}
目的地:
public class Model
{
public Address BillingAddress { get; set; }
public Address MailingAddress { get; set; }
public string Name { get; set; }
}
public class Address
{
public decimal? Latitude { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public decimal? Longitude { get; set; }
public string PostalCode { get; set; }
public string Unit { get; set; }
}
这是我的地图尝试。
CreateMap<ViewModel, Address>();
CreateMap<ViewModel, Model>()
.ForMember(d => d.BillingAddress, o => o.MapFrom(s => s))
.ForMember(d => d.MailingAddress, o => o.MapFrom(s => s));
这使我两个地址都初始化了,但属性始终为空。
如果在任何配置中都没有自动填充此属性,则我将接受失败并会分别映射每个属性。
谢谢您的输入。
答案 0 :(得分:0)
这有效
映射
public class ReverseMappingProfile : Profile
{
public ReverseMappingProfile()
{
RecognizeDestinationPrefixes("Billing", "Mailing");
CreateMap<Model, ViewModel>()
.ReverseMap();
CreateMap<Address, ViewModel>()
.ReverseMap();
}
}
配置
var mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new ReverseMappingProfile());
});
IMapper mapper = mappingConfig.CreateMapper();
执行
var model = new Model
{
Name = "Joe Bloggs",
BillingAddress = new Address
{
Line1 = "Line 1",
Line2 = "Line 1",
Line3 = "Line 1",
PostalCode = "ABCDEF",
Latitude = 1232,
Longitude = 4321,
Unit = "A Unit"
},
MailingAddress = new Address
{
Line1 = "M Line 1",
Line2 = "M Line 1",
Line3 = "M Line 1",
PostalCode = "MMFDS",
Latitude = 6543,
Longitude = 78990,
Unit = "M Unit"
},
};
var viewModel = mapper.Map<ViewModel>(model);
var newModel = mapper.Map<Model>(viewModel);