[英]MongoDB c# Driver - Perform a LINQ “Any” in a Serialized Dictionary
I have a document type with some attributes, one of which is a Dictionary< string, string >. 我有一个带有一些属性的文档类型,其中一个是Dictionary <string,string>。
Serialization and De-serealization seem to work fine (I can search, perform CRUD operations, etc.). 序列化和去实现似乎工作正常(我可以搜索,执行CRUD操作等)。 The problem is that I'm trying to write a method to find all the objects of that type where the dictionary contains a specific value (id) among its Keys.
问题是我正在尝试编写一个方法来查找该类型的所有对象,其中字典在其Keys中包含特定值(id)。
Attempted Query: 试图查询:
var objectCollection = db.GetCollection<MyClass>("MyClass");
var query = Query<MyClass>.Where(m => m.MyDictionary.Any(k => k.Key == id));
The Class: 班级:
public class MyClass
{
public ObjectId Id { get; set; }
// ...
[BsonElement("Dictionary")]
public Dictionary<string, string> MyDictionary { get; set; }
}
...but I get this Exception while building the query: ...但我在构建查询时遇到此异常:
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.
I suspect the problem is related to the fact that the c# driver's default serializer doesn't support this. 我怀疑这个问题与c#驱动程序的默认序列化程序不支持这个问题有关。 Is there a workaround?
有解决方法吗?
I've also tried to perform a "Contains" for the id
string on the Dictionary.Keys
collection, but that gives a NotSupportedException: Unable to determine the serialization information for the expression: m.Dictionary.Keys.
我还试图对
Dictionary.Keys
集合上的id
字符串执行“Contains”,但是这会产生NotSupportedException: Unable to determine the serialization information for the expression: m.Dictionary.Keys.
Figured it out on my own... 我自己想出来......
Added an annotation in MyClass
to specify how I want the Dictionary to be serialized ( read about DictionarySerializationOptions here for more info). 在
MyClass
添加了一个注释,以指定我希望如何序列化Dictionary ( 有关更多信息,请阅读DictionarySerializationOptions )。
[BsonElement("Dictionary")]
[BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)] // Added This!
public Dictionary<string, string> Dictionary { get; set; }
This serializes the Dictionary as an array of Documents, each containing a "k" (key) and "v" (value). 这将Dictionary序列化为一个Documents数组,每个Document包含一个“k”(键)和“v”(值)。
Then I changed my query to: 然后我将查询更改为:
var query = Query.ElemMatch("Dictionary", Query.EQ("k", id));
This searches entries in my collection in which the Dictionary contains id
as one of its keys. 这将搜索我的集合中的条目,其中Dictionary包含
id
作为其键之一。
Other relevant links: 其他相关链接:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.