How do I set the serialization options for the geo values using the official 10gen C# driver?

安稳与你 提交于 2019-12-22 08:13:36

问题


Considering this class:

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

I have a geospatial index on the collection set like { Geo: "2d" }. Unfortunately the driver tries to store lat/lon coordinates as strings, instead of numbers and I get an error that says Tue Mar 15 16:29:22 [conn8] insert database.locations exception 13026 geo values have to be numbers: { Lat: "50.0853779", Long: "19.931276700000012" } 1ms. To alleviate this problem I setup a map like this:

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

Notice that there is no BsonType.Decimal nor anything like that. In the effect, when trying to call Save() I get a MongoDB.Bson.TruncationException, which seems logical. What are my options?


回答1:


According this bug(fixed Jan 21 2011 05:46:23 AM UTC), in c# official driver was added ability 'AllowTruncation'. So you need download latest driver version and enjoy! Also instead of SetRepresentation you can use BsonRepresentationAttribute like this:

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


来源:https://stackoverflow.com/questions/5314238/how-do-i-set-the-serialization-options-for-the-geo-values-using-the-official-10g

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!