【发布时间】:2020-08-25 06:32:38
【问题描述】:
我正在开发一个应用程序,它使用IDocumentClient 来执行对 CosmosDB 的查询。我的GenericRepository支持Id和Predicate查询。
将数据库从 SqlServer 更改为 CosmosDb 时遇到麻烦,在 CosmosDb 中,我们有 partition key。而且我不知道如何实现支持partition key 查询的存储库,而无需更改接口以将partition key 作为参数传递。
public interface IRepository<T>
{
//I can handle this one by adding value of partition key to id and split it by ":"
Task<T> FindByIdAsync(string id);
// I am stuck here!!!
Task<T> FindByPredicateAsync(Expression<Func<T, bool>> predicate);
}
我的实现
public class Repository<T> : IRepository<T>
{
private readonly IDocumentClient _documentClient;
private readonly string _databaseId;
private readonly string _collectionId;
public Repository(IDocumentClient documentClient, string databaseId, string collectionId)
{
_documentClient = documentClient;
_databaseId = databaseId;
_collectionId = collectionId;
}
public async Task<T> FindByIdAsync(string id)
{
var documentUri = UriFactory.CreateDocumentUri(_databaseId, _collectionId, id);
try
{
var result = await _documentClient.ReadDocumentAsync<TDocument>(documentUri, new RequestOptions
{
PartitionKey = ParsePartitionKey(documentId)
});
return result.Document;
}
catch (DocumentClientException e)
{
if (e.StatusCode == HttpStatusCode.NotFound)
{
throw new EntityNotFoundException();
}
throw;
}
}
public async Task<T> FindByPredicateAsync(Expression<Func<T, bool>> predicate)
{
//Need to query CosmosDb with partition key here!
}
private PartitionKey ParsePartitionKey(string entityId) => new PartitionKey(entityId.Split(':')[0]);
}
非常感谢任何帮助,谢谢。
【问题讨论】:
-
可以举出这些函数的例子让我们更好的理解吗?并显示您的 FindByIdAsync 代码的外观。
-
我已经更新了问题。请再次检查,谢谢。
-
希望能帮助 CosmosDB 用户理解并给你更好的答案。
标签: c# .net-core repository azure-cosmosdb data-partitioning