[英]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.