use*_*392 5 c# linq mongodb mongodb-query mongodb-.net-driver
我有一个带有一些属性的文档类型,其中之一是 Dictionary<string, string>。
序列化和反序列化似乎工作正常(我可以搜索、执行 CRUD 操作等)。问题是我正在尝试编写一种方法来查找该类型的所有对象,其中字典在其键中包含特定值 (id)。
尝试查询:
var objectCollection = db.GetCollection<MyClass>("MyClass");
var query = Query<MyClass>.Where(m => m.MyDictionary.Any(k => k.Key == id));
Run Code Online (Sandbox Code Playgroud)
班上:
public class MyClass
{
public ObjectId Id { get; set; }
// ...
[BsonElement("Dictionary")]
public Dictionary<string, string> MyDictionary { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
...但我在构建查询时遇到此异常:
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.
Run Code Online (Sandbox Code Playgroud)
我怀疑这个问题与 c# 驱动程序的默认序列化程序不支持这一事实有关。有解决方法吗?
我还尝试对集合中的id字符串执行“包含” Dictionary.Keys,但这给出了一个NotSupportedException: Unable to determine the serialization information for the expression: m.Dictionary.Keys.
自己想出来的。。。
添加了一个注释MyClass以指定我希望如何序列化字典(在此处阅读 DictionarySerializationOptions以获取更多信息)。
[BsonElement("Dictionary")]
[BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)] // Added This!
public Dictionary<string, string> Dictionary { get; set; }
Run Code Online (Sandbox Code Playgroud)
这将字典序列化为文档数组,每个文档包含一个“k”(键)和“v”(值)。
然后我将查询更改为:
var query = Query.ElemMatch("Dictionary", Query.EQ("k", id));
Run Code Online (Sandbox Code Playgroud)
这将在我的集合中搜索字典包含id作为其键之一的条目。
其他相关链接: