如何在投射到查询时忽略AutoMapper中的属性,但仍将其映射为结果

本文关键字:属性 结果 映射 AutoMapper 查询 | 更新日期: 2023-09-27 18:03:35

我有一个实体,它包含一个具有多多边形的DbGeography类型。我已经将DbGeography映射到字符串[][]:

internal class DbGeographyAutoMapper : Profile
{
    public DbGeographyAutoMapper()
    {
        CreateMap<DbGeography, string[][]>()
            .ConvertUsing(geo =>
            {
                var maxElement = geo.ElementCount + 1;
                var rings = new string[geo.ElementCount.Value][];
                for (var elementIndex = 1; elementIndex < maxElement; elementIndex++)
                {
                    var currentElement = geo.ElementAt(elementIndex);
                    var latLngs = new string[currentElement.PointCount.Value];
                    var max = currentElement.PointCount + 1;
                    for (var i = 1; i < max; i++)
                    {
                        var point = currentElement.PointAt(i).EndPoint;
                        latLngs[i - 1] = $"{Math.Round(point.Latitude.Value, 4)},{Math.Round(point.Longitude.Value, 4)}";
                    }
                    rings[elementIndex - 1] = latLngs;
                }
                return rings;
            });
    }
}

和实体到包含字符串[][]的模型:

internal class WireCenterAutoMapper : Profile
{
    public WireCenterAutoMapper()
    {
        CreateMap<WireCenter, WirecenterModel>()
            .ForMember(m => m.Boundary, m => m.MapFrom(wc => wc.Boundary)) // This is the DbGeography to string[][]
            .ForMember(m => m.CLLI, m => m.MapFrom(wc => wc.CLLI))
            .ForMember(m => m.Id, m => m.MapFrom(wc => wc.Id))
            .ForMember(m => m.Name, m => m.MapFrom(wc => wc.OCN))
            .ForMember(m => m.Owner, m => m.MapFrom(wc => wc.Incumbent))
            .ForMember(m => m.State, m => m.MapFrom(wc => wc.State));
    }
}

当我尝试将它投影到一个IQueryable…

[EnableQuery(PageSize = 500)]
public async Task<IQueryable<WirecenterModel>> Get([FromUri] BoundingBox intersects = null)
{
    return (await _wireCentersRepository.Find(intersects)).ProjectTo<WirecenterModel>();
}

…它会爆炸,因为DbGeography使用了一个转换。我想在将该属性从实体转换为模型时将其映射,但在将其投影到EF查询时忽略它。我把它标记为NotMapped…

/// <summary>
///     The Wire Center's boundary
/// </summary>
[NotMapped]
public string[][] Boundary { get; set; }

…但这无济于事。我该怎么做呢?

如何在投射到查询时忽略AutoMapper中的属性,但仍将其映射为结果

我有一个类似的问题,我不想在ProjectTo()期间特别映射。

对我来说有效的是ExplicitExpansion设置:

internal class WireCenterAutoMapper : Profile
{
    public WireCenterAutoMapper()
    {
        CreateMap<WireCenter, WirecenterModel>()
            .ForMember(m => m.Boundary, opt => opt.ExplicitExpansion()) 
//...Followed by the rest of the code
    }
}

这样,LINQ投影不会映射该值,将其保留为空,除非您显式地请求将其映射到投影中。