关于Microsoft.Azure.DocumentDB v1.20.2中IDocumentClient缺失Create..IfNotExists方法的咨询
关于IDocumentClient缺少Create..IfNotExists方法的解答
首先明确:这确实是官方的有意设计。
为什么接口不包含这些方法?
Microsoft.Azure.DocumentDB的IDocumentClient接口只暴露了Cosmos DB(当时还叫DocumentDB)的核心原子操作,而Create..IfNotExists这类方法本质是客户端层面的封装——它们的逻辑是先尝试查询资源是否存在,如果不存在再执行创建操作。官方没有把这些封装方法放到接口里,是为了保持接口的简洁性,同时让开发者可以根据自己的需求实现定制化的存在性检查逻辑。
替代方案
方案1:直接使用DocumentClient实例
如果你的代码不需要依赖抽象接口(比如不需要做单元测试的mock),可以直接声明变量为DocumentClient类型,这样就能直接调用所有Create..IfNotExists方法:
var client = new DocumentClient(new Uri(endpoint), authKey); var collection = await client.CreateDocumentCollectionIfNotExistsAsync( UriFactory.CreateDatabaseUri("MyDatabase"), new DocumentCollection { Id = "MyCollection" } );
方案2:给IDocumentClient写扩展方法
如果需要保持对IDocumentClient接口的依赖,可以自己封装扩展方法来实现相同的逻辑。比如针对CreateDocumentCollectionIfNotExistsAsync的扩展:
public static class DocumentClientExtensions { public static async Task<ResourceResponse<DocumentCollection>> CreateDocumentCollectionIfNotExistsAsync( this IDocumentClient client, Uri databaseUri, DocumentCollection collection, RequestOptions options = null) { try { return await client.ReadDocumentCollectionAsync( UriFactory.CreateDocumentCollectionUri(databaseUri.Segments[1].TrimEnd('/'), collection.Id), options); } catch (DocumentClientException ex) when (ex.StatusCode == HttpStatusCode.NotFound) { return await client.CreateDocumentCollectionAsync(databaseUri, collection, options); } } }
这样你就可以通过IDocumentClient接口直接调用这个扩展方法,和原生的Create..IfNotExists逻辑一致。
类似地,你可以用同样的思路封装CreateDatabaseIfNotExistsAsync、CreateDocumentIfNotExistsAsync等方法——核心都是先尝试读取资源,捕获NotFound异常后再执行创建。
内容的提问来源于stack exchange,提问作者yanis
相关产品推荐
相关产品推荐

