3

ElemMatch を使用して、2.2 ドライバーを使用して MongoDB でドキュメントを検索しようとしていますが、成功しません。次のような例外が発生します。

System.InvalidOperationException : フィールド 'EnabledForProduct' のシリアライザーは、IBsonArraySerializer を実装し、アイテムのシリアル化情報を提供する必要があります。

私のクラスは次のようになります。

public class Document
{
  public string Id {get; set;}
  public Dictionary<Product, bool> EnabledForProduct { get; set; }
}
public enum Product {Product1,Product2};

私の ClassMap は次のようになります。

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>()));
});

次のようなフィルターを使用しようとすると、例外が発生します。

Builders<Document>.Filter.ElemMatch(f => f.EnabledForProduct,
    x => x.Key == Product1 && x.Value))

これは、1.x ドライバーで問題なく動作していました。

私が間違っていることを誰かが知っていますか?

4

1 に答える 1

3

さて、いくつかの試行錯誤の実装の後、必要なことを行う方法を見つけました。モデル クラスを直接使用する代わりに、次のように ElemMatch フィルターのためだけに BsonDocument コレクションを使用することになりました。

var bsonCollection = database.GetCollection<BsonDocument>("testcollection");

フィルタは次のように作成されます。

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)));

また、BsonSerializer を使用して、汎用の BsonDocument をモデル クラスに逆シリアル化できます。

var foundDoc = BsonSerializer.Deserialize<Document>(bsonCollection.Find(filter).Limit(1).FirstOrDefault());
于 2016-01-04T23:58:10.170 に答える