【问题标题】:MongoDB c# Driver - Perform a LINQ "Any" in a Serialized DictionaryMongoDB c# 驱动程序 - 在序列化字典中执行 LINQ“任何”
【发布时间】:2014-05-19 12:03:06
【问题描述】:

我有一个带有一些属性的文档类型,其中之一是 Dictionary。

序列化和 去序列化 似乎工作正常(我可以搜索、执行 CRUD 操作等)。问题是我正在尝试编写一个方法来查找该类型的所有对象,其中字典在其键中包含特定值(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 字符串执行“包含”,但这给出了NotSupportedException: Unable to determine the serialization information for the expression: m.Dictionary.Keys.

【问题讨论】:

  • 也许您可以先尝试将 m.MyDictionary.Keys 转换为列表,然后再放入 linq? var listOfKeys = m.Dictionary.Keys.ToList();
  • 不是:NotSupportedException: Unable to determine the serialization information for the expression: Enumerable.ToList&lt;String&gt;(m.Dictionary.Keys). 也是。

标签: c# linq mongodb mongodb-.net-driver mongodb-query


【解决方案1】:

我自己想出来的...

在MyClass 中添加了一个注释来指定我希望如何序列化字典(read about DictionarySerializationOptions here 了解更多信息)。

[BsonElement("Dictionary")]
[BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)] // Added This!
public Dictionary<string, string> Dictionary { get; set; }

这会将 Dictionary 序列化为 Documents 数组,每个 Documents 包含一个“k”(键)和“v”(值)。

然后我将查询更改为:

var query = Query.ElemMatch("Dictionary", Query.EQ("k", id));

这会搜索我的集合中 Dictionary 包含 id 作为其键之一的条目。

其他相关链接:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    相关资源
    最近更新 更多