简体   繁体   中英

Dynamically build query for Azure DocumentDB

I recently swichted from MongoDB to Azure DocumentDB and want check if a duplicate document exists in the collection by dynamically building a query.

This is how I solved the query building with 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();
    }
}

Right now I am using LINQ to check for duplicates in 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();
}

How can I dynamically build the where clause like Query.And(clauses) using DocumentDB?

Thanks

I think something like this will do what you're looking for. Since LINQ allows where clauses to be chained (a natural AND), you can build the query as follows:

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

Note: you can step through the debugger and the ToString() representation will show the SQL translation for the LINQ query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM