【问题标题】:How do I set the serialization options for the geo values using the official 10gen C# driver?如何使用官方 10gen C# 驱动程序设置地理值的序列化选项?
【发布时间】:2011-03-15 15:46:09
【问题描述】:

考虑这个类:

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" }。不幸的是,驱动程序尝试将纬度/经度坐标存储为字符串,而不是数字,我收到一条错误消息,提示 Tue Mar 15 16:29:22 [conn8] insert database.locations exception 13026 geo values must be numbers: { 纬度:“50.0853779”,长:“19.931276700000012”} 1 毫秒。为了缓解这个问题,我设置了这样的地图:

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,这似乎是合乎逻辑的。我有哪些选择?

【问题讨论】:

    标签: c# serialization mongodb mongodb-.net-driver


    【解决方案1】:

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

    【讨论】:

    • 是的,我知道我可以使用属性,但我只是选择不这样做,我不想在我的域模型中出现更多依赖项。
    • @Pawel:所以 AllowTruncation=true 在新版本中工作?因为我没有实际测试过,我也想知道。
    • 是的,确实如此,我在SetRepresentation() 中找不到它(想知道为什么它没有放在那里...),而是必须通过SetSerializationOptions(new RepresentationSerializationOptions(BsonType.Double, false, true)) 设置它。或者属性,当然。我不想降低精度,但看看地图我猜它“足够好”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    • 2018-08-08
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    相关资源
    最近更新 更多