How to query BsonExtraElements in MongoDB via Linq

断了今生、忘了曾经 提交于 2019-12-07 14:01:19

问题


I used the mongodb [BsonExtraElements] feature to extend my class some dynamic data, but unfortunately I cannot create a query by mongodb C# driver.

Here is my model class:

public class MongoProductEntity 
{
    public MongoProductEntity()
    {
        AdditionalColumns = new BsonDocument { AllowDuplicateNames = false };
    }
    [BsonExtraElements]
    public BsonDocument AdditionalColumns { get; set; }
    public string BrandName { get; set; }
}

Here is the query part:

        var productEntity = new MongoProductEntity ()
        {
            BrandName = "Brand"
        };            
        productEntity.AdditionalColumns.Add("testProperty", 6);
        productEntity.AdditionalColumns.Add("testProperty2", "almafa");

        await productEntityRepo.InsertAsync(productEntity);
        var qq = productEntityRepo.Where(x => x.AdditionalColumns["testProperty"] == 6).ToList();

This query returns no one element from database, however if I'm trying to query the BrandName property everything is working fine!

Is there anyone who faced similar situation or know why that query is not woking? Thx in advance!

Just a short remark here: the type of productEntityRepo is a wrapper over the MongoDb MongoProductEntity collection and this wrapper returns the collection as Queryable, that's all. I'm using MongoDb 3.2.9, with the latest C# Driver 2.2.4.


回答1:


Since version 2.3 of the C# driver it is possible to use the .Inject() method on a FilterDefinition<T>:

var filter = Builders<BsonDocument>.Filter.Eq("testProperty2", "almafa");
productEntityRepo.Where((dbModel) => dbModel.BrandName == "Brand" && filter.Inject());

This should allow you express filters that are difficult, or impossible, to describe via LINQ. You will need to update from 2.2.4 to the newer version though.



来源:https://stackoverflow.com/questions/39603151/how-to-query-bsonextraelements-in-mongodb-via-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!