简体   繁体   中英

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

I'm trying to query a set of GeoJSON in a Mongo database. 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:

    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:

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

But this generates a query in Mongo which looks like this:

"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. Deserialisation from the string works fine.

How can I make the Mongo driver generate the correct query?

I had to register a serialiser for the enum type at startup, like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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