编程语言
首页 > 编程语言> > 如何使用官方10gen C#驱动程序为地理值设置序列化选项?

如何使用官方10gen C#驱动程序为地理值设置序列化选项?

作者:互联网

考虑这个课程:

public class Location
{
    public Coordinates Geo { get; set; }

    public Location()
    {
        Geo = new Coordinates();
    }

    public class Coordinates
    {
        public decimal Lat { get; set; }
        public decimal Long { get; set; }
    }
}

我在集合集上有一个地理空间索引,如{Geo:“2d”}.不幸的是,驱动程序试图将lat / lon坐标存储为字符串,而不是数字,我得到一个错误,上面写着Tue Mar 15 16:29:22 [conn8] insert database.locations exception 13026 geo values必须是数字:{Lat: “50.0853779”,长:“19.931276700000012”} 1ms.为了缓解这个问题,我设置了这样的地图:

BsonClassMap.RegisterClassMap<Location.Coordinates>(cm =>
{
    cm.AutoMap();
    cm.MapProperty(c => c.Lat).SetRepresentation(BsonType.Double);
    cm.MapProperty(c => c.Long).SetRepresentation(BsonType.Double);
});

请注意,没有BsonType.Decimal,也没有类似的东西.在效果中,当尝试调用Save()时,我得到一个MongoDB.Bson.TruncationException,这似乎是合乎逻辑的.我有什么选择?

解决方法:

根据这个bug(fixed Jan 21 2011 05:46:23 AM UTC),在c#官方驱动程序中添加了“AllowTruncation”功能.所以你需要下载最新的驱动版本并享受!也可以使用BsonRepresentationAttribute代替SetRepresentation,如下所示:

public class C {
  [BsonRepresentation(BsonType.Double, AllowTruncation=true)]
  public decimal D;
}

标签:c,serialization,mongodb,mongodb-net-driver
来源: https://codeday.me/bug/20190626/1296849.html