如何通过Linq在MongoDB中查询BsonExtraElements [英] How to query BsonExtraElements in MongoDB via Linq

查看:244
本文介绍了如何通过Linq在MongoDB中查询BsonExtraElements的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用mongodb [BsonExtraElements]功能扩展了我的类的一些动态数据,但不幸的是,我无法通过mongodb C#驱动程序创建查询.

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

这是我的模特班:

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

这是查询部分:

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

此查询没有从数据库返回任何元素,但是,如果我尝试查询BrandName属性,一切正常!

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!

这里只是简短的一句话:productEntityRepo的类型是MongoDb MongoProductEntity集合的包装,而该包装将集合返回为Queryable,仅此而已.我使用的是MongoDb 3.2.9,以及最新的C#驱动程序2.2.4.

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.

推荐答案

由于

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

这应该允许您表达难以或不可能通过LINQ描述的过滤器.不过,您需要从2.2.4更新到新版本.

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.

这篇关于如何通过Linq在MongoDB中查询BsonExtraElements的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆