我在类中具有默认构造函数以提供值automapper的属性时如何进行映射?

问题描述 投票:-1回答:1

我想创建从UserDto到用户实体的映射,请帮助我如何实现此目标。我在用户实体中具有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; }
    }

GeoLocation类:

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个回答
2
投票

您可以参考此代码:

 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);
© www.soinside.com 2019 - 2024. All rights reserved.