如何使用 AutoMapper 映射到具有继承和嵌套模型的模型
我有一个具有 2 个子类型的地址实体。这是我的简化代码:
public class Address {
public string Street1 { get; set; }
public string Country { get; set; }
}
public class UsAddress : Address {
public string State { get; set; }
}
public class CandianAddress : Address {
public string Providence { get; set; }
}
这是我的简化视图模型:
public class LocationModel {
public string Street1 { get; set; }
}
public class UsLocationModel : LocationModel {
public string State { get; set; }
}
public class CaLocationModel : LocationModel {
public string Providence { get; set; }
}
public class AddressModel {
public int? Country { get; set; }
public UsLocationModel UsLocation { get; set; }
public CaLocationModel CaLocation { get; set; }
}
这是我简化的 AutoMapper 配置:
Mapper.CreateMap<Address, AddressModel>()
.Include<UsAddress, AddressModel>()
.Include<CanadianAddress, AddressModel>();
Mapper.CreateMap<UsAddress, AddressModel>();
Mapper.CreateMap<CanadianAddress, AddressModel>();
Mapper.CreateMap<Address, LocationModel>()
.Include<UsAddress, USLocationModel>()
.Include<CanadianAddress, CALocationModel>();
Mapper.CreateMap<UsAddress, USLocationModel>();
Mapper.CreateMap<CanadianAddress, CALocationModel>();
我不知道如何解析 AddressModel 上的
...UsLocation
和 CaLocation
属性
I have an Address entity with 2 sub types. Here's my simplified code:
public class Address {
public string Street1 { get; set; }
public string Country { get; set; }
}
public class UsAddress : Address {
public string State { get; set; }
}
public class CandianAddress : Address {
public string Providence { get; set; }
}
Here's my simplified view models:
public class LocationModel {
public string Street1 { get; set; }
}
public class UsLocationModel : LocationModel {
public string State { get; set; }
}
public class CaLocationModel : LocationModel {
public string Providence { get; set; }
}
public class AddressModel {
public int? Country { get; set; }
public UsLocationModel UsLocation { get; set; }
public CaLocationModel CaLocation { get; set; }
}
Here's my simplified AutoMapper config:
Mapper.CreateMap<Address, AddressModel>()
.Include<UsAddress, AddressModel>()
.Include<CanadianAddress, AddressModel>();
Mapper.CreateMap<UsAddress, AddressModel>();
Mapper.CreateMap<CanadianAddress, AddressModel>();
Mapper.CreateMap<Address, LocationModel>()
.Include<UsAddress, USLocationModel>()
.Include<CanadianAddress, CALocationModel>();
Mapper.CreateMap<UsAddress, USLocationModel>();
Mapper.CreateMap<CanadianAddress, CALocationModel>();
I can't figure out how to resolve the UsLocation
and CaLocation
properties on AddressModel
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想通了。这是我的 Automapper 配置的简化版本:
这是一个简化的示例测试:
I figured it out. Here's a simplified version of my Automapper config:
Here's a simplified sample test: