【问题标题】:Dynamically build query for Azure DocumentDB为 Azure DocumentDB 动态构建查询
【发布时间】:2015-04-11 23:14:24
【问题描述】:

我最近从 MongoDB 切换到 Azure DocumentDB,想通过动态构建查询来检查集合中是否存在重复文档。

这就是我使用 MongoDB 解决查询构建的方法:

MongoCollection collection = mongoDbDatabase.GetCollection<BsonDocument>("123");
var clauses = new List<IMongoQuery>();

foreach (var currResult in Results)
{
    //add query
    clauses.Add(Query.EQ("_result", currResult));
    clauses.Add(Query.EQ("_id", myId));
}

var query = (clauses.Count > 0) ? Query.And(clauses) : null;

if (query != null)
{
    //check if we have at least one duplicate
    if (collection.FindOneAs<BsonDocument>(query) != null)
    {
        DoSomething();
    }
}

现在我正在使用 LINQ 检查 DocumentDB 中的重复项:

var result = (from c in documentDb.CreateDocumentQuery<Results>(collection.SelfLink)
              where c.result = currResult &&
              c.id == myId
              select c).AsEnumerable();
int numResults = result.Count();
if(numResults > 0)
{
    DoSomething();
}

如何使用 DocumentDB 动态构建类似 Query.And(clauses) 的 where 子句?

谢谢

【问题讨论】:

    标签: c# linq azure azure-cosmosdb


    【解决方案1】:

    我认为这样的事情会满足您的需求。由于 LINQ 允许链接 where 子句(自然与),您可以按如下方式构建查询:

    var result = new Stuff { A = "a", B = "b" };
    IQueryable<Stuff> query = client.CreateDocumentQuery<Stuff>(collectionLink);
    if (result != null)
    {
        query = query.Where(s => s.A == result.A);
        query = query.Where(s => s.B == result.B);
    }
    
    int numResults = query.AsEnumerable().Count();
    if (numResults > 0)
    {
        // DoSomething();
    }
    

    注意:您可以单步调试调试器,ToString() 表示将显示 LINQ 查询的 SQL 转换。

    【讨论】:

    • 谢谢,它在比较整数时有效,但在以这种方式比较字符串或日期时间时出现错误。 “'myString' 附近的语法不正确”和“不支持 'System.DateTime' 类型的常量。”做查询时。AsEnumerable().Count()
    • 使用 IEnumerable 查询 = client.CreateDocumentQuery(collectionLink);而不是 IQueryable 帮助。
    猜你喜欢
    • 1970-01-01
    • 2012-11-23
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 2012-12-21
    • 2018-12-21
    • 1970-01-01
    相关资源
    最近更新 更多