简体   繁体   English

MongoDB C# 驱动程序:LINQ 对枚举进行过滤将枚举序列化为 int

[英]MongoDB C# driver: LINQ filtering on enum serialises enum as int

I'm trying to query a set of GeoJSON in a Mongo database.我正在尝试在 Mongo 数据库中查询一组 GeoJSON。 Documents look a bit like this:文档看起来有点像这样:

{
    "_id" : ObjectId("5db2d9d7a9912b215bb6bfc8"),
    "type" : "Feature",
    "properties" : {
//snip
    },
    "geometry" : {
        "type" : "Polygon",
        "coordinates" : [ //snip ]
}
}

My C# class for the geometry property looks like this:我的几何属性的 C# class 如下所示:

    public class Geometry
    {

        [JsonProperty("type")]
        [BsonElement("type")]
        [BsonRepresentation(BsonType.String)]
        public GeometryType Type { get; set; }
}

However I have some LINQ filtering code a bit like this:但是我有一些 LINQ 过滤代码有点像这样:

Builders<Feature>.Filter.Ne(f => f.Geometry.Type, GeometryType.LineString)

But this generates a query in Mongo which looks like this:但这会在 Mongo 中生成一个查询,如下所示:

"geometry.type" : {
                "$ne" : 1
            }

This doesn't filter as expected because it's serialising LineString as 1, not "LineString" which is how it's represented in the database.这没有按预期过滤,因为它将 LineString 序列化为 1,而不是“LineString”,这是它在数据库中的表示方式。 Deserialisation from the string works fine.从字符串反序列化工作正常。

How can I make the Mongo driver generate the correct query?如何让 Mongo 驱动程序生成正确的查询?

I had to register a serialiser for the enum type at startup, like this:我必须在启动时为枚举类型注册一个序列化器,如下所示:

BsonSerializer.RegisterSerializer(new EnumSerializer<GeometryType>(BsonType.String));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM