You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用AutoMapper将坐标实体列表映射为GeoEvent的二维数组属性

解决方案

你可以通过以下两种方式实现该属性的映射:

方式一:内嵌转换逻辑(适合单次使用场景)

直接在MapFrom方法内编写二维数组转换逻辑:

CreateMap<IEnumerable<GeoCoordinateEntity>, GeoEvent>()
    .ForMember(
        dest => dest.GeometryType,
        opt => opt.MapFrom(src => GeometryType.LineString))
    .ForMember(
        dest => dest.Coordinates,
        opt => opt.MapFrom(src => 
        {
            var coordinateList = src.ToList();
            var coordinates = new double[coordinateList.Count, 2];
            for (int i = 0; i < coordinateList.Count; i++)
            {
                // GeoJSON规范要求坐标顺序为 [经度, 纬度],请勿调换顺序
                coordinates[i, 0] = coordinateList[i].Longitude;
                coordinates[i, 1] = coordinateList[i].Latitude;
            }
            return coordinates;
        }));

方式二:自定义类型转换器(适合多场景复用)

先实现AutoMapper的ITypeConverter接口定义通用转换逻辑:

public class GeoCoordinateTo2DArrayConverter : ITypeConverter<IEnumerable<GeoCoordinateEntity>, double[,]>
{
    public double[,] Convert(IEnumerable<GeoCoordinateEntity> source, double[,] destination, ResolutionContext context)
    {
        var coordinateList = source.ToList();
        var coordinates = new double[coordinateList.Count, 2];
        for (int i = 0; i < coordinateList.Count; i++)
        {
            coordinates[i, 0] = coordinateList[i].Longitude;
            coordinates[i, 1] = coordinateList[i].Latitude;
        }
        return coordinates;
    }
}

再修改映射配置调用转换器即可:

CreateMap<IEnumerable<GeoCoordinateEntity>, GeoEvent>()
    .ForMember(
        dest => dest.GeometryType,
        opt => opt.MapFrom(src => GeometryType.LineString))
    .ForMember(
        dest => dest.Coordinates,
        opt => opt.ConvertUsing<GeoCoordinateTo2DArrayConverter>());

注意事项

  • 如果你不需要严格遵循GeoJSON规范,可以根据业务需求调整Longitude和Latitude的赋值顺序。

内容的提问来源于stack exchange,提问作者Randi Ratnayake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 08:39:03