From the new CosmosDb emulator, I got a kind of repository for performing basic documentdb operations, this repository is introduced into other classes. I wanted a unit test base query.
public class DocumentDBRepository<T> where T : class
{
public IQueryable<T> GetQueryable()
{
return _client.CreateDocumentQuery<T>(
UriFactory.CreateDocumentCollectionUri(_databaseId, _collectionId),
new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = true });
}
public async Task<IEnumerable<T>> ExecuteQueryAsync(IQueryable<T> query)
{
IDocumentQuery<T> documentQuery = query.AsDocumentQuery();
List<T> results = new List<T>();
while (documentQuery.HasMoreResults)
{
results.AddRange(await documentQuery.ExecuteNextAsync<T>());
}
return results;
}
}
For this repository, you need a document client for work, which is also entered into the constructor.
public DocumentDBRepository(string databaseId, IDocumentClient client)
{
_client = client;
_databaseId = databaseId;
_collectionId = GetCollectionName();
}
My initial approach was to use the CosmosDb emulator, but for this I had to run an emulator that I don't like, and makes tests slower.
My second approach was to try using a document client layout.
var data = new List<MyDocumentClass>
{
new MyDocumentClass{ Description= "BBB" },
new MyDocumentClass{ Description= "ZZZ" },
}
.AsQueryable()
.OrderBy(q => q.Description);
var client = new Mock<IDocumentClient>();
client.As<IDocumentClient>()
.Setup(foo => foo.CreateDocumentQuery<MyDocumentClass>(It.IsAny<Uri>(), It.IsAny<FeedOptions>()))
.Returns(data);
DocumentDBRepository<MyDocumentClass> repo= new DocumentDBRepository<MyDocumentClass>(cosmosDatabase, client.Object);
The code that uses this repository works as follows:
var query = _documentsRepository.GetQueryable()
.Where(d => d.Description = description)
.OrderByDescending(d => d.description)
.Take(100);
var result = await _documentsRepository.ExecuteQueryAsync(query);
, IQueryable
IDocumentQuery
, DocumentDb api (. ExecuteQueryAsync
). HasMoreResults
. , .asDocumentQuery()
, , HasMoreResults
ExecuteNextAsync
, .
DocumentClient. , , , DocumentDb api.