首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >带有字典的MongoDB C# 2.x驱动程序ElemMatch

带有字典的MongoDB C# 2.x驱动程序ElemMatch
EN

Stack Overflow用户
提问于 2015-12-31 05:35:47
回答 1查看 1.6K关注 0票数 3

我试图使用ElemMatch在MongoDB中使用2.2驱动程序找到一个文档,但没有成功。我收到一个例外情况,例如:

System.InvalidOperationException :字段'EnabledForProduct‘的序列化程序必须实现IBsonArraySerializer并提供项序列化信息。

我的课是这样的:

代码语言:javascript
运行
复制
public class Document
{
  public string Id {get; set;}
  public Dictionary<Product, bool> EnabledForProduct { get; set; }
}
public enum Product {Product1,Product2};

我的ClassMap看起来像这样:

代码语言:javascript
运行
复制
BsonClassMap.RegisterClassMap<Document>(cm =>
{
    cm.AutoMap();
    cm.MapMember(c => c.EnabledForProduct)
      .SetSerializer(new DictionaryInterfaceImplementerSerializer<Dictionary<Product, bool>>(DictionaryRepresentation.ArrayOfDocuments, 
                        BsonSerializer.LookupSerializer<int>(), 
                        BsonSerializer.LookupSerializer<bool>()));
});

当尝试使用筛选器时会出现异常,例如:

代码语言:javascript
运行
复制
Builders<Document>.Filter.ElemMatch(f => f.EnabledForProduct,
    x => x.Key == Product1 && x.Value))

这过去在1.x驱动程序中是完美无缺的。

有人知道我做错了什么吗?

EN

回答 1

Stack Overflow用户

发布于 2016-01-04 23:58:10

嗯,经过一些尝试和错误实现之后,我想出了一种方法来做我需要的事情。我没有直接使用模型类,而是使用了一个BsonDocument集合,只用于ElemMatch过滤器,如下所示:

代码语言:javascript
运行
复制
var bsonCollection = database.GetCollection<BsonDocument>("testcollection");

过滤器的创建方式如下:

代码语言:javascript
运行
复制
var filter = Builders<BsonDocument>.Filter.ElemMatch("EnabledForProduct", Builders<BsonDocument>.Filter.And(Builders<BsonDocument>.Filter.Eq("k",(int)Product.Product1),Builders<BsonDocument>.Filter.Eq("v",true)));

并且可以使用BsonDocument将泛型BsonSerializer反序列化回模型类:

代码语言:javascript
运行
复制
var foundDoc = BsonSerializer.Deserialize<Document>(bsonCollection.Find(filter).Limit(1).FirstOrDefault());
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34541589

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档