如何解决:无法将类型为“ MongoDB.Bson.BsonArray”的对象转换为类型为“ MongoDB.Bson.BsonBoolean”的

时间:2019-10-27 12:43:17

标签: c# mongodb api

我目前正在使用MongoDb $ GeoWithin查询处理API GET方法。如果我使用断点检查代码,则会看到查询正在返回结果。但是,当我的应用程序应该返回响应时,我在Postman中收到了错误(500)响应。

我似乎无法弄清楚到底出了什么问题。我看到“无法将类型为“ MongoDB.Bson.BsonArray”的对象转换为类型为“ MongoDB.Bson.BsonBoolean”。”在stacktrace中,但是我的Model / MongoDb文档没有任何问题。

免责声明:我当前的代码很乱,但是我只是想在重构它之前使它起作用。

我的模特

public class Bag3DMember
    {
        [BsonId]
        [DataMember]
        [BsonElement("_id")]
        public string _Id { get; set; }

        [DataMember]
        [BsonElement("type")]
        public string Type { get; set; }

        [BsonElement("geometry")]
        public Geometry Geometry { get; set; }

        [BsonElement("geometry_name")]
        public string GeometryName { get; set; }

        [BsonElement("properties")]
        public Properties Properties { get; set; }

    }

    public class Geometry
    {
        [BsonElement("type")]
        public string Type { get; set; }

        [BsonElement("coordinates")]
        public BsonArray Coordinates { get; set; }
    }

    public class Properties
    {
        [BsonElement("gid")]
        public int Gid { get; set; }

        [BsonElement("identificatie")]
        public string Identificatie { get; set; }

        [BsonElement("aanduidingrecordinactief")]
        public bool AanduidingrecordInactief { get; set; }

        [BsonElement("aanduidingrecordcorrectie")]
        public int AanduidingrecordCorrectie { get; set; }

        [BsonElement("officieel")]
        public bool Officieel { get; set; }

        [BsonElement("inonderzoek")]
        public bool InOnderzoek { get; set; }

        [BsonElement("documentnummer")]
        public string DocumentNummer { get; set; }

        [BsonElement("documentdatum")]
        public string DocumentDatum { get; set; }

        [BsonElement("bouwjaar")]
        public string Bouwjaar { get; set; }

        [BsonElement("begindatumtijdvakgeldigheid")]
        public string BeginDatumTijdVakGeldigheid { get; set; }

        [BsonElement("einddatumtijdvakgeldigheid")]
        public string EindDatumTijdVakGeldigheid { get; set; }

        [BsonElement("gemeentecode")]
        public string GemeenteCode { get; set; }

        [BsonElement("ground-000")]
        public decimal? Ground000 { get; set; }

        [BsonElement("ground-010")]
        public decimal? Ground010 { get; set; }

        [BsonElement("ground-020")]
        public decimal? Ground020 { get; set; }

        [BsonElement("ground-030")]
        public decimal? Ground030 { get; set; }

        [BsonElement("ground-040")]
        public decimal? Ground040 { get; set; }

        [BsonElement("ground-050")]
        public decimal? Ground050 { get; set; }

        [BsonElement("roof-025")]
        public decimal? Roof025 { get; set; }

        [BsonElement("roof-050")]
        public decimal? Roof050 { get; set; }

        [BsonElement("roof-075")]
        public decimal? Roof075 { get; set; }

        [BsonElement("roof-090")]
        public decimal? Roof090 { get; set; }

        [BsonElement("roof-095")]
        public decimal? Roof095 { get; set; }

        [BsonElement("roof-099")]
        public decimal? Roof099 { get; set; }

        [BsonElement("rmse-025")]
        public decimal? Rmse025 { get; set; }

        [BsonElement("rmse-050")]
        public decimal? Rmse050 { get; set; }

        [BsonElement("rmse-075")]
        public decimal? Rmse075 { get; set; }

        [BsonElement("rmse-090")]
        public decimal? Rmse090 { get; set; }

        [BsonElement("rmse-095")]
        public decimal? Rmse095 { get; set; }

        [BsonElement("rmse-099")]
        public decimal? Rmse099 { get; set; }

        [BsonElement("roof_flat")]
        public bool RoofFlat { get; set; }

        [BsonElement("nr_ground_pts")]
        public int NrGroundPts { get; set; }

        [BsonElement("nr_roof_pts")]
        public int NrRoofPts { get; set; }

        [BsonElement("ahn_file_date")]
        public string AhnFileDate { get; set; }

        [BsonElement("ahn_version")]
        public int AhnVersion { get; set; }

        [BsonElement("height_valid")]
        public bool HeightValid { get; set; }

        [BsonElement("tile_id")]
        public string TileId { get; set; }

        [BsonElement("bbox")]
        public BsonArray[] BoundingBox { get; set; }
    }

我的控制器方法:

[HttpGet]
        public ActionResult<List<Bag3DMember>> Get(string coordinates, double radius)
        {
            if(coordinates == null || radius == 0)
            {
                return StatusCode(400, "Paramaters: 'coordinates' and/or 'radius' are not found.");
            }

            var splittedCoordinates = coordinates.Split(',');

            if(splittedCoordinates.Length != 2)
            {
                return StatusCode(406, "Coordinatesformat not accepted.");
            }

            var formattedCoordinates = Array.ConvertAll(splittedCoordinates, s => double.Parse(s, CultureInfo.InvariantCulture));

            FieldDefinition<Bag3DMember> field = "bbox";
            var results = _bag3DService.GetBySpatialQuery(field, formattedCoordinates[0], formattedCoordinates[1], radius);
            var jsonResults = Json(results);
            return Json(results);
        }

数据库服务方法

public List<Bag3DMember> GetBySpatialQuery(FieldDefinition<Bag3DMember> field, double x, double y, double radius)
        {
            //var filter = Builders<Bag3DMember>.Filter.GeoWithinBox(field, (x - (radius/2)), (y - (radius / 2)), (x + (radius / 2)), (y + (radius / 2)));
            BsonArray lowerLeftDoc = new BsonArray(new[] { 0, 0 });
            BsonArray upperRightDoc = new BsonArray(new[] { 10000000, 10000000 });
            BsonArray boundingBox = new BsonArray(new[] { lowerLeftDoc, upperRightDoc });

            BsonDocument locBox = new BsonDocument { { "$box", boundingBox } };
            BsonDocument locDoc = new BsonDocument { { "$geoWithin", locBox } };
            BsonDocument queryDoc = new BsonDocument { { "properties.bbox", locDoc } };

            var results = _Bag3DMembers.Find(new QueryDocument(queryDoc)).ToList();

            return results;
        }

因此在Visual Studio中,它成功返回查询。如您所见,它从数据库返回一个文档: results

JSON对象:

{
    "$type": "System.Collections.Generic.List<EnveoApi.Bag3DMember>",
    "$values": [
        {
            "$type": "EnveoApi.Bag3DMember",
            "_Id": "pand3d.8575483",
            "Type": "Feature",
            "Geometry": {
                "$type": "EnveoApi.Geometry",
                "Type": "Polygon",
                "Coordinates": {
                    "$type": "MongoDB.Bson.BsonArray",
                    "$values": [
                        {
                            "$type": "MongoDB.Bson.BsonArray",
                            "$values": [
                                {
                                    "$type": "MongoDB.Bson.BsonArray",
                                    "$values": [
                                        108665.593,
                                        447232.925,
                                        0
                                    ]
                                },
                                {
                                    "$type": "MongoDB.Bson.BsonArray",
                                    "$values": [
                                        108667.648,
                                        447229.102,
                                        0
                                    ]
                                },
                                {
                                    "$type": "MongoDB.Bson.BsonArray",
                                    "$values": [
                                        108676.807,
                                        447234.217,
                                        0
                                    ]
                                },
                                {
                                    "$type": "MongoDB.Bson.BsonArray",
                                    "$values": [
                                        108674.334,
                                        447238.579,
                                        0
                                    ]
                                },
                                {
                                    "$type": "MongoDB.Bson.BsonArray",
                                    "$values": [
                                        108665.593,
                                        447232.925,
                                        0
                                    ]
                                }
                            ]
                        }
                    ]
                }
            },
            "GeometryName": "geovlak",
            "Properties": {
                "$type": "EnveoApi.Properties",
                "Gid": 8575483,
                "Identificatie": "0513100011121832",
                "AanduidingrecordInactief": "false",
                "AanduidingrecordCorrectie": 0,
                "Officieel": "false",
                "InOnderzoek": "false",
                "DocumentNummer": "BAGAV1776",
                "DocumentDatum": "2018-08-15Z",
                "Bouwjaar": "1900-01-01Z",
                "BeginDatumTijdVakGeldigheid": "2018-08-14T22:00:00Z",
                "EindDatumTijdVakGeldigheid": null,
                "GemeenteCode": "0513",
                "Ground000": -0.44,
                "Ground010": -0.42,
                "Ground020": -0.41,
                "Ground030": -0.41,
                "Ground040": -0.4,
                "Ground050": -0.39,
                "Roof025": 2.72,
                "Roof050": 2.81,
                "Roof075": 3.03,
                "Roof090": 4.76,
                "Roof095": 7.04,
                "Roof099": 9.72,
                "Rmse025": 0.87,
                "Rmse050": 0.62,
                "Rmse075": 0.62,
                "Rmse090": 0.62,
                "Rmse095": 0.62,
                "Rmse099": 0.62,
                "RoofFlat": "false",
                "NrGroundPts": 12,
                "NrRoofPts": 1247,
                "AhnFileDate": "2014-02-25T23:00:00Z",
                "AhnVersion": 3,
                "HeightValid": "true",
                "TileId": "38an2",
                "BoundingBox": {
                    "$type": "MongoDB.Bson.BsonArray[]",
                    "$values": [
                        {
                            "$type": "MongoDB.Bson.BsonArray",
                            "$values": [
                                108665.593,
                                447229.102
                            ]
                        },
                        {
                            "$type": "MongoDB.Bson.BsonArray",
                            "$values": [
                                108676.807,
                                447238.579
                            ]
                        }
                    ]
                }
            }
        }
    ]
}

我在Visual Studio 2019中没有收到任何错误。我仅在Postman(堆栈跟踪)中得到了错误:

System.InvalidCastException: Unable to cast object of type 'MongoDB.Bson.BsonArray' to type 'MongoDB.Bson.BsonBoolean'.
   at get_AsBoolean(Object )
   at System.Text.Json.JsonPropertyInfoNotNullable`4.OnWrite(WriteStackFrame& current, Utf8JsonWriter writer)
   at System.Text.Json.JsonPropertyInfo.Write(WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.JsonSerializer.HandleObject(JsonPropertyInfo jsonPropertyInfo, JsonSerializerOptions options, Utf8JsonWriter writer, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteObject(JsonSerializerOptions options, Utf8JsonWriter writer, WriteStack& state)
   at System.Text.Json.JsonSerializer.Write(Utf8JsonWriter writer, Int32 originalWriterDepth, Int32 flushThreshold, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, Object value, Type inputType, JsonSerializerOptions options, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Mvc.Infrastructure.SystemTextJsonResultExecutor.ExecuteAsync(ActionContext context, JsonResult result)
   at Microsoft.AspNetCore.Mvc.Infrastructure.SystemTextJsonResultExecutor.ExecuteAsync(ActionContext context, JsonResult result)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeResultFilters>g__Awaited|27_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Accept: */*
Accept-Encoding: gzip, deflate
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:44348
User-Agent: PostmanRuntime/7.19.0
Postman-Token: c23588a0-0e6b-46f8-834c-93dbfc6134eb

编辑1:

如果我注释掉“几何”中所有嵌套的“属性”和“坐标”,似乎可以使用。

显然,“坐标”给了我一个问题。但是“属性”中也有文档给我带来了问题。但是我仍然不明白为什么它试图将BsonArray(坐标为)转换为布尔值?

此外,我现在仅返回结果,而不是Json(results)。但这没什么区别。

修改2: 如果使它动态,那么“坐标”将起作用。但是我认为这是不好的做法吧?

 public class Geometry
{
    [BsonElement("type")]
    public string Type { get; set; }

    [BsonElement("coordinates")]
    public dynamic Coordinates { get; set; }
}

2 个答案:

答案 0 :(得分:0)

我遇到了这个问题,我的解决方法是将我的通用收藏夹更改为,并且一切正常,并且可以使用任何模型结构。示例:DB.GetCollection(“集合名称”);

答案 1 :(得分:0)

当前已解决了建议的原始海报问题。使用动态而不是BsonDocument,BsonArray或您的任何类型都不起作用的方式。在动态和瞧之间切换!