当我的类中有属性具有默认构造函数来提供值自动映射器时,如何映射?
Posted
技术标签:
【中文标题】当我的类中有属性具有默认构造函数来提供值自动映射器时,如何映射?【英文标题】:How can I map when I've property in my class which have default constructor to provide values automapper? 【发布时间】:2020-07-14 00:43:08 【问题描述】:我想创建一个从 UserDto 到 User 实体的映射,请帮助我如何实现这一点。我在用户实体中有 GeoLocation 属性,如何映射这些属性。有人可以举个例子吗?
我正在使用 AutoMapper 包:https://www.nuget.org/packages/AutoMapper/
我的用户实体类:
public class User
public string Id get; set;
public string Name get; set;
public GeoLocation PurchaseLocationCoordinates get; set;
我的 Dto 课程:
public class UserDto
public string Id get; set; = Guid.NewGuid().ToString();
public string Name get; set;
public string PurchaseLocationLatitude get; set;
public string PurchaseLocationLongitude get; set;
地理位置类:
public class GeoLocation
public GeoLocation(double lon, double lat)
Type = "Point";
if (lat > 90 || lat < -90) throw new ArgumentException("A latitude coordinate must be a value between -90.0 and +90.0 degrees.");
if (lon > 180 || lon < -180) throw new ArgumentException("A longitude coordinate must be a value between -180.0 and +180.0 degrees.");
Coordinates = new double[2] lon, lat ;
[JsonProperty("type")]
public string Type get; set;
[JsonProperty("coordinates")]
public double[] Coordinates get; set;
public double? Lat() => Coordinates?[1];
public double? Lon() => Coordinates?[0];
映射:
CreateMap<UserDto, User>();
【问题讨论】:
docs.automapper.org/en/latest/Construction.html 【参考方案1】:你可以参考这段代码:
var config = new MapperConfiguration(cfg =>
cfg.CreateMap<UserDto, User>()
.ForMember(x => x.PurchaseLocationCoordinates, opt => opt.MapFrom(model => model));
cfg.CreateMap<UserDto, GeoLocation>()
.ForCtorParam("lon", opt => opt.MapFrom(src => src.PurchaseLocationLongitude))
.ForCtorParam("lat", opt => opt.MapFrom(src => src.PurchaseLocationLatitude));
);
UserDto userdto = new UserDto()
PurchaseLocationLongitude = "80.44",
PurchaseLocationLatitude = "34.56"
;
IMapper iMapper = config.CreateMapper();
var user = iMapper.Map<UserDto, User>(userdto);
【讨论】:
不需要double.Parse
。 AM 默认会这样做。
感谢您的解决方案。我接受了你的回答。以上是关于当我的类中有属性具有默认构造函数来提供值自动映射器时,如何映射?的主要内容,如果未能解决你的问题,请参考以下文章
自定义对象映射器 bean 更改打开 Feign 客户端的默认属性/自动配置的 objectMapper bean