【问题标题】:How to query BsonExtraElements in MongoDB via Linq如何通过 Linq 在 MongoDB 中查询 BsonExtraElements
【发布时间】:2016-09-20 20:24:42
【问题描述】:

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

这是我的模型类:

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 属性,一切正常!

有没有人遇到过类似的情况或知道为什么该查询不起作用? 提前谢谢!

这里只是一个简短的说明:productEntityRepo 的类型是 MongoDb MongoProductEntity 集合的包装器,这个包装器将集合返回为 Queryable,仅此而已。我使用的是 MongoDb 3.2.9,最新的 C# Driver 2.2.4。

【问题讨论】:

    标签: c# .net mongodb mongodb-query


    【解决方案1】:

    由于 C# 驱动程序的 version 2.3 可以在 FilterDefinition<T> 上使用 .Inject() 方法:

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

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

    【讨论】:

      猜你喜欢
      • 2010-10-08
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多