[英]MongoDB c# Driver - Perform a LINQ “Any” in a Serialized Dictionary
我有一个带有一些属性的文档类型,其中一个是Dictionary <string,string>。
序列化和去实现似乎工作正常(我可以搜索,执行CRUD操作等)。 问题是我正在尝试编写一个方法来查找该类型的所有对象,其中字典在其Keys中包含特定值(id)。
试图查询:
var objectCollection = db.GetCollection<MyClass>("MyClass");
var query = Query<MyClass>.Where(m => m.MyDictionary.Any(k => k.Key == id));
班级:
public class MyClass
{
public ObjectId Id { get; set; }
// ...
[BsonElement("Dictionary")]
public Dictionary<string, string> MyDictionary { get; set; }
}
...但我在构建查询时遇到此异常:
Any requires that the serializer specified for Dictionary support items by implementing
MongoDB.Bson.Serialization.IBsonArraySerializer and returning a non-null result.
MongoDB.Bson.Serialization.Serializers.DictionarySerializer`2[System.String,System.String]
is the current serializer.
我怀疑这个问题与c#驱动程序的默认序列化程序不支持这个问题有关。 有解决方法吗?
我还试图对Dictionary.Keys
集合上的id
字符串执行“Contains”,但是这会产生NotSupportedException: Unable to determine the serialization information for the expression: m.Dictionary.Keys.
我自己想出来......
在MyClass
添加了一个注释,以指定我希望如何序列化Dictionary ( 有关更多信息,请阅读DictionarySerializationOptions )。
[BsonElement("Dictionary")]
[BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)] // Added This!
public Dictionary<string, string> Dictionary { get; set; }
这将Dictionary序列化为一个Documents数组,每个Document包含一个“k”(键)和“v”(值)。
然后我将查询更改为:
var query = Query.ElemMatch("Dictionary", Query.EQ("k", id));
这将搜索我的集合中的条目,其中Dictionary包含id
作为其键之一。
其他相关链接:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.