从Microsoft.Azure.DocumentDb迁移到Microsoft.Azure.Cosmos的类兼容方案问询
Cosmos DB v2 到 v3 迁移:Document/Resource/AccessCondition 替代方案
1. 实体类替代原 Resource/Document
原v2里Resource类自带的id、Timestamp、SelfLink等系统属性,在v3里可以通过自定义基类+JsonProperty映射Cosmos原生系统字段实现,查询时会自动填充这些属性:
先定义通用基类:
public abstract class CosmosResource { [JsonProperty(PropertyName = "id")] public string Id { get; set; } // 对应原Timestamp,Cosmos原生字段为_ts(时间戳秒数) [JsonProperty(PropertyName = "_ts")] public long Timestamp { get; set; } // 对应原SelfLink,Cosmos原生字段为_self [JsonProperty(PropertyName = "_self")] public string SelfLink { get; set; } // 若需要ETag(原Resource的ETag属性),也可以加上 [JsonProperty(PropertyName = "_etag")] public string ETag { get; set; } }
改造业务实体类:
public class WorkPlay : CosmosResource { [JsonProperty(PropertyName = "WorkTypeEnum")] public string WorkTypeEnum { get; set; } [JsonProperty(PropertyName = "MediaType")] public string MediaType { get; set; } [JsonProperty(PropertyName = "Product")] public string Product { get; set; } }
这样用v3 API查询文档时,_self字段会自动映射到SelfLink属性,完全兼容旧代码依赖。
2. AccessCondition 与 AccessConditionType 的替代
v3移除了AccessCondition类,改用ItemRequestOptions的IfMatchEtag和IfNoneMatchEtag属性实现并发控制:
- 原
AccessConditionType.IfNoneMatch→ 对应IfNoneMatchEtag = "*" - 原
AccessConditionType.IfMatch→ 对应IfMatchEtag = "具体ETag值"
原v2读文档代码迁移后:
// 初始化v3 CosmosClient(建议单例复用,不要重复创建) this._cosmosClient = new CosmosClient(this._endpoint, this._authKey); // 获取目标容器 var container = _cosmosClient.GetContainer("你的数据库名", "你的容器名"); // 替代原AccessCondition.IfNoneMatch逻辑 var requestOptions = new ItemRequestOptions { IfNoneMatchEtag = "*" }; // 方式1:用ID+分区键读取(推荐) var response = await container.ReadItemAsync<WorkPlay>(Item1.Id, new PartitionKey(你的分区键值), requestOptions); // 方式2:直接用SelfLink读取(兼容旧代码依赖) var response = await _cosmosClient.ReadItemAsync<WorkPlay>(new Uri(Item1.SelfLink), requestOptions);
3. 基于SelfLink的删除操作迁移
v3支持直接通过SelfLink的Uri执行删除操作,不需要额外传分区键(SelfLink已包含所有必要路径信息):
public async Task DeleteItemAsync(string selfLink) { await _cosmosClient.DeleteItemAsync<WorkPlay>(new Uri(selfLink), new ItemRequestOptions()); }
额外注意事项
- v3的
CosmosClient是线程安全的,建议全局单例实例化,避免频繁创建销毁 - 原
ResourceResponse<Document>的替代是ItemResponse<T>,包含StatusCode、ETag、ResponseHeaders等相同维度的信息 - v3 API命名更直观,比如
CreateItemAsync替代CreateDocumentAsync
内容的提问来源于stack exchange,提问作者Abhash786
相关产品推荐
相关产品推荐

