C#ASP.NET API:设置MongoDb ID

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

我正在尝试使用MongoDb作为数据库来设置ASP.NET API,并且目前正在尝试将JSON对象插入数据库。但是由于某种原因,我无法为数据库设置自定义ID。

如果我让MongoDb自动生成一个ID,没有问题,我可以简单地将JSON对象放入数据库中:

{"_id":"5db0b2cf6abcc72fa42c8991","id":"pand3d.8575483","type":"Feature","geometry":{"type":"Polygon","coordinates":[[[108665.593,447232.925,0],[108667.648,447229.102,0],[108676.807,447234.217,0],[108674.334,447238.579,0],[108665.593,447232.925,0]]]},"geometry_name":"geovlak","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","ground-000":"-0.44","ground-010":"-0.42","ground-020":"-0.41","ground-030":"-0.41","ground-040":"-0.4","ground-050":"-0.39","roof-025":"2.72","roof-050":"2.81","roof-075":"3.03","roof-090":"4.76","roof-095":"7.04","roof-099":"9.72","rmse-025":"0.87","rmse-050":"0.62","rmse-075":"0.62","rmse-090":"0.62","rmse-095":"0.62","rmse-099":"0.62","roof_flat":false,"nr_ground_pts":12,"nr_roof_pts":1247,"ahn_file_date":"2014-02-25T23:00:00Z","ahn_version":3,"height_valid":true,"tile_id":"38an2","bbox":["108665.593","447229.102","108676.807","447238.579"]}}

但是您会看到,它会生成一个{“ _id”:“ 5db0b2cf6abcc72fa42c8991”}作为ID。但是我希望{“ id”:“ pand3d.8575483”}充当ID。

所以我制作了这个模型:

 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; }

}

但是当我将JSON对象插入数据库时​​,出现此错误消息:

System.FormatException:'元素'id'与EnveoApi.Bag3DMember类的任何字段或属性都不匹配。'

c# asp.net mongodb api
1个回答
0
投票

请尝试以下操作并回复...

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; }

}

在您的代码中,将对Bag3DMember.id的引用更改为Bag3DMember._id

© www.soinside.com 2019 - 2024. All rights reserved.