【问题标题】: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>();

【问题讨论】:

标签: c# .net asp.net-core mapping automapper


【解决方案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 默认会这样做。
  • 感谢您的解决方案。我接受了你的回答。
猜你喜欢
  • 2015-02-25
  • 1970-01-01
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
  • 2013-01-14
  • 1970-01-01
  • 2022-10-08
  • 1970-01-01
相关资源
最近更新 更多