AzureCosmosDBV3Repository.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. using Microsoft.Azure.Cosmos;
  2. using Microsoft.Azure.Cosmos.Linq;
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Linq.Expressions;
  8. using System.Net;
  9. using System.Reflection;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using TEAMModelOS.SDK.Context.Attributes.Azure;
  13. using TEAMModelOS.SDK.Context.Exception;
  14. using TEAMModelOS.SDK.Helper.Common.ReflectorExtensions;
  15. using TEAMModelOS.SDK.Module.AzureCosmosDB.Configuration;
  16. namespace TEAMModelOS.SDK.Module.AzureCosmosDBV3
  17. {
  18. public class AzureCosmosDBV3Repository : IAzureCosmosDBV3Repository, IDisposable
  19. {
  20. private CosmosClient CosmosClient { get; set; }
  21. /// <summary>
  22. /// 线程安全的dict类型
  23. /// </summary>
  24. private Dictionary<string, Container> DocumentCollectionDict { get; set; } = new Dictionary<string, Container>();
  25. private string DatabaseId { get; set; }
  26. private int CollectionThroughput { get; set; }
  27. private Database database = null;
  28. private string[] ScanModel { get; set; }
  29. public AzureCosmosDBV3Repository(AzureCosmosDBOptions options, CosmosSerializer cosmosSerializer)
  30. {
  31. try
  32. {
  33. if (!string.IsNullOrEmpty(options.ConnectionString))
  34. {
  35. CosmosClient = CosmosDBV3ClientSingleton.getInstance(options.ConnectionString, options.ConnectionKey, cosmosSerializer).GetCosmosDBClient();
  36. }
  37. else
  38. {
  39. throw new BizException("请设置正确的AzureCosmosDB数据库配置信息!");
  40. }
  41. DatabaseId = options.Database;
  42. CollectionThroughput = options.CollectionThroughput;
  43. ScanModel = options.ScanModel;
  44. // InitializeDatabase().GetAwaiter().GetResult();
  45. }
  46. catch (CosmosException e)
  47. {
  48. Dispose(true);
  49. throw new BizException(e.Message, 500, e.StackTrace);
  50. }
  51. }
  52. public AzureCosmosDBV3Repository(AzureCosmosDBOptions options)
  53. {
  54. try
  55. {
  56. if (!string.IsNullOrEmpty(options.ConnectionString))
  57. {
  58. CosmosClient = CosmosDBV3ClientSingleton.getInstance(options.ConnectionString, options.ConnectionKey, null).GetCosmosDBClient();
  59. }
  60. else
  61. {
  62. throw new BizException("请设置正确的AzureCosmosDB数据库配置信息!");
  63. }
  64. DatabaseId = options.Database;
  65. CollectionThroughput = options.CollectionThroughput;
  66. ScanModel = options.ScanModel;
  67. // InitializeDatabase().GetAwaiter().GetResult();
  68. }
  69. catch (CosmosException e)
  70. {
  71. Dispose(true);
  72. throw new BizException(e.Message, 500, e.StackTrace);
  73. }
  74. }
  75. public async Task InitializeDatabase()
  76. {
  77. try
  78. {
  79. database = await CosmosClient.CreateDatabaseIfNotExistsAsync(DatabaseId, CollectionThroughput);
  80. FeedIterator<ContainerProperties> resultSetIterator = database.GetContainerQueryIterator<ContainerProperties>();
  81. while (resultSetIterator.HasMoreResults)
  82. {
  83. foreach (ContainerProperties container in await resultSetIterator.ReadNextAsync())
  84. {
  85. DocumentCollectionDict.TryAdd(container.Id, database.GetContainer(container.Id));
  86. }
  87. }
  88. //获取数据库所有的表
  89. List<Type> types = ReflectorExtensions.GetAllTypeAsAttribute<CosmosDBAttribute>(ScanModel);
  90. foreach (Type type in types)
  91. {
  92. string PartitionKey = GetPartitionKey(type);
  93. string CollectionName = "";
  94. int RU = 0;
  95. IEnumerable<CosmosDBAttribute> attributes = type.GetCustomAttributes<CosmosDBAttribute>(true);
  96. if (!string.IsNullOrEmpty(attributes.First<CosmosDBAttribute>().Name))
  97. {
  98. CollectionName = attributes.First<CosmosDBAttribute>().Name;
  99. }
  100. else
  101. {
  102. CollectionName = type.Name;
  103. }
  104. if (attributes.First<CosmosDBAttribute>().RU > 400)
  105. {
  106. RU = attributes.First<CosmosDBAttribute>().RU;
  107. }
  108. else
  109. {
  110. RU = CollectionThroughput;
  111. }
  112. //如果表存在于数据则检查RU是否变动,如果不存在则执行创建DocumentCollection
  113. if (DocumentCollectionDict.TryGetValue(CollectionName, out Container collection))
  114. { //更新RU
  115. int? throughputResponse = await CosmosClient.GetDatabase(DatabaseId).GetContainer(collection.Id).ReadThroughputAsync();
  116. if (throughputResponse < RU)
  117. {
  118. await CosmosClient.GetDatabase(DatabaseId).GetContainer(collection.Id).ReplaceThroughputAsync(RU);
  119. }
  120. }
  121. else
  122. {
  123. ContainerProperties containerProperties = new ContainerProperties { Id = CollectionName };
  124. if (!string.IsNullOrEmpty(PartitionKey))
  125. {
  126. containerProperties.PartitionKeyPath = "/" + PartitionKey;
  127. }
  128. if (RU > CollectionThroughput)
  129. {
  130. CollectionThroughput = RU;
  131. }
  132. Container containerWithConsistentIndexing = await database.CreateContainerIfNotExistsAsync(containerProperties, throughput: CollectionThroughput);
  133. DocumentCollectionDict.TryAdd(CollectionName, containerWithConsistentIndexing);
  134. }
  135. }
  136. }
  137. catch (CosmosException e)
  138. {
  139. throw new BizException(e.Message, 500, e.StackTrace);
  140. }
  141. }
  142. private string GetPartitionKey<T>()
  143. {
  144. Type type = typeof(T);
  145. return GetPartitionKey(type);
  146. }
  147. private string GetPartitionKey(Type type)
  148. {
  149. PropertyInfo[] properties = type.GetProperties();
  150. List<PropertyInfo> attrProperties = new List<PropertyInfo>();
  151. foreach (PropertyInfo property in properties)
  152. {
  153. if (property.Name.Equals("PartitionKey"))
  154. {
  155. attrProperties.Add(property);
  156. break;
  157. }
  158. object[] attributes = property.GetCustomAttributes(true);
  159. foreach (object attribute in attributes) //2.通过映射,找到成员属性上关联的特性类实例,
  160. {
  161. if (attribute is PartitionKeyAttribute)
  162. {
  163. attrProperties.Add(property);
  164. }
  165. }
  166. }
  167. if (attrProperties.Count <= 0)
  168. {
  169. throw new BizException(type.Name + "has no PartitionKey !");
  170. }
  171. else
  172. {
  173. if (attrProperties.Count == 1)
  174. {
  175. return attrProperties[0].Name;
  176. }
  177. else { throw new BizException("PartitionKey can only be single!"); }
  178. }
  179. }
  180. private async Task<Container> InitializeCollection<T>()
  181. {
  182. Type type = typeof(T);
  183. string partitionKey = GetPartitionKey<T>();
  184. string CollectionName;
  185. IEnumerable<CosmosDBAttribute> attributes = type.GetCustomAttributes<CosmosDBAttribute>(true);
  186. if (!string.IsNullOrEmpty(attributes.First<CosmosDBAttribute>().Name))
  187. {
  188. CollectionName = attributes.First<CosmosDBAttribute>().Name;
  189. }
  190. else
  191. {
  192. CollectionName = type.Name;
  193. }
  194. return await InitializeCollection(CollectionName, partitionKey);
  195. }
  196. private async Task<Container> InitializeCollection(string CollectionName, string PartitionKey)
  197. {
  198. /////内存中已经存在这个表则直接返回
  199. if (DocumentCollectionDict.TryGetValue(CollectionName, out Container DocumentCollection))
  200. {
  201. return DocumentCollection;
  202. }///如果没有则尝试默认创建
  203. else
  204. {
  205. ContainerProperties containerProperties = new ContainerProperties { Id = CollectionName };
  206. if (!string.IsNullOrEmpty(PartitionKey))
  207. {
  208. containerProperties.PartitionKeyPath = "/" + PartitionKey;
  209. }
  210. Container containerWithConsistentIndexing = await database.CreateContainerIfNotExistsAsync(containerProperties, throughput: CollectionThroughput);
  211. DocumentCollectionDict.TryAdd(CollectionName, containerWithConsistentIndexing);
  212. return containerWithConsistentIndexing;
  213. }
  214. }
  215. public async Task DeleteAll<T>(List<KeyValuePair<string, string>> ids) where T : ID
  216. {
  217. string partitionKey = GetPartitionKey<T>();
  218. await Task.Run(() => Parallel.ForEach(ids, (item) =>
  219. {
  220. Task.WaitAll(DeleteAsync<T>(item.Value, item.Key));
  221. }));
  222. }
  223. public async Task DeleteAll<T>(List<T> entities) where T : ID
  224. {
  225. string partitionKey = GetPartitionKey<T>();
  226. Type type = typeof(T);
  227. await Task.Run(() => Parallel.ForEach(entities, (item) =>
  228. {
  229. object o = type.GetProperty(partitionKey).GetValue(item, null);
  230. Task.WaitAll(DeleteAsync<T>(item.id, o.ToString()));
  231. }));
  232. }
  233. public async Task<T> DeleteAsync<T>(string id, string pk) where T : ID
  234. {
  235. Container container = await InitializeCollection<T>();
  236. ItemResponse<T> response = await container.DeleteItemAsync<T>(id: id, partitionKey: new PartitionKey(pk));
  237. return response.Resource;
  238. }
  239. public async Task<T> DeleteAsync<T>(T entity) where T : ID
  240. {
  241. Container container = await InitializeCollection<T>();
  242. string partitionKey = GetPartitionKey<T>();
  243. Type type = typeof(T);
  244. object o = type.GetProperty(partitionKey).GetValue(entity, null);
  245. ItemResponse<T> response = await container.DeleteItemAsync<T>(id: entity.id, partitionKey: new PartitionKey(o.ToString()));
  246. return response.Resource;
  247. }
  248. //public async Task<T> DeleteAsync<T>(string id) where T : ID
  249. //{
  250. // Container container = await InitializeCollection<T>();
  251. // ItemResponse<T> response = await container.DeleteItemAsync<T>(id: id, partitionKey: new PartitionKey(GetPartitionKey<T>()));
  252. // return response.Resource;
  253. //}
  254. public async Task<List<T>> FindAll<T>() where T : ID
  255. {
  256. Container container = await InitializeCollection<T>();
  257. return await ResultsFromFeedIterator(container.GetItemQueryIterator<T>());
  258. }
  259. private async Task<List<T>> ResultsFromFeedIterator<T>(FeedIterator<T> query, int? maxItemCount = null)
  260. {
  261. List<T> results = new List<T>();
  262. while (query.HasMoreResults)
  263. {
  264. foreach (T t in await query.ReadNextAsync())
  265. {
  266. results.Add(t);
  267. if (results.Count == maxItemCount)
  268. {
  269. return results;
  270. }
  271. }
  272. }
  273. return results;
  274. }
  275. private async Task<List<T>> ResultsFromFeedIterator<T>(FeedIterator<T> query, Func<List<T>, Task> batchAction, int itemsPerPage)
  276. {
  277. List<T> results = new List<T>();
  278. while (query.HasMoreResults)
  279. {
  280. if (results.Count() >= itemsPerPage)
  281. {
  282. await batchAction(results);
  283. results.Clear();
  284. }
  285. results.AddRange(await query.ReadNextAsync());
  286. }
  287. if (results.Count() > 0)
  288. {
  289. await batchAction(results);
  290. results.Clear();
  291. }
  292. return results;
  293. }
  294. public async Task<List<dynamic>> FindByDict(string CollectionName, Dictionary<string, object> dict, int itemsPerPage = -1, int? maxItemCount = null, string partitionKey = null)
  295. {
  296. if (DocumentCollectionDict.TryGetValue(CollectionName, out Container container))
  297. {
  298. //StringBuilder sql = new StringBuilder("select value(c) from c");
  299. //SQLHelper.GetSQL(dict, ref sql);
  300. //CosmosDbQuery cosmosDbQuery = new CosmosDbQuery
  301. //{
  302. // QueryText = sql.ToString()
  303. //};
  304. StringBuilder sql = new StringBuilder("select value(c) from c");
  305. CosmosDbQuery cosmosDbQuery = SQLHelperParametric.GetSQL(dict, sql);
  306. QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(itemsPerPage, maxItemCount));
  307. FeedIterator<dynamic> query = container.GetItemQueryIterator<dynamic>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryRequestOptions);
  308. return await ResultsFromFeedIterator(query, maxItemCount);
  309. }
  310. else
  311. {
  312. throw new BizException("CollectionName named:" + CollectionName + " dose not exsit in Database!");
  313. }
  314. }
  315. public async Task<List<dynamic>> FindCountByDict(string CollectionName, Dictionary<string, object> dict, int itemsPerPage = -1, int? maxItemCount = null, string partitionKey = null)
  316. {
  317. if (DocumentCollectionDict.TryGetValue(CollectionName, out Container container))
  318. {
  319. //StringBuilder sql = new StringBuilder("select value count(c) from c");
  320. //SQLHelper.GetSQL(dict, ref sql);
  321. //CosmosDbQuery cosmosDbQuery = new CosmosDbQuery
  322. //{
  323. // QueryText = sql.ToString()
  324. //};
  325. StringBuilder sql = new StringBuilder("select value count(c) from c");
  326. CosmosDbQuery cosmosDbQuery = SQLHelperParametric.GetSQL(dict, sql);
  327. QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(itemsPerPage, maxItemCount));
  328. FeedIterator<dynamic> query = container.GetItemQueryIterator<dynamic>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryRequestOptions);
  329. return await ResultsFromFeedIterator(query, maxItemCount);
  330. }
  331. else
  332. {
  333. throw new BizException("CollectionName named:" + CollectionName + " dose not exsit in Database!");
  334. }
  335. }
  336. public async Task<List<T>> FindByParams<T>(Dictionary<string, object> dict, int itemsPerPage = -1, int? maxItemCount = null, string partitionKey = null) where T : ID
  337. {
  338. return await FindByDict<T>(dict, itemsPerPage, maxItemCount, partitionKey);
  339. }
  340. public async Task<List<T>> FindByDict<T>(Dictionary<string, object> dict, int itemsPerPage = -1, int? maxItemCount = null, string partitionKey = null) where T : ID
  341. {
  342. StringBuilder sql = new StringBuilder("select value(c) from c");
  343. CosmosDbQuery cosmosDbQuery = SQLHelperParametric.GetSQL(dict,sql);
  344. QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(itemsPerPage, maxItemCount));
  345. return await ResultsFromQueryAndOptions<T>(cosmosDbQuery, queryRequestOptions);
  346. }
  347. private async Task<List<T>> ResultsFromQueryAndOptions<T>(CosmosDbQuery cosmosDbQuery, QueryRequestOptions queryOptions, int? maxItemCount = null)
  348. {
  349. Container container = await InitializeCollection<T>();
  350. FeedIterator<T> query = container.GetItemQueryIterator<T>(
  351. queryDefinition: cosmosDbQuery.CosmosQueryDefinition,
  352. requestOptions: queryOptions);
  353. return await ResultsFromFeedIterator(query, maxItemCount);
  354. }
  355. private int GetEffectivePageSize(int itemsPerPage, int? maxItemCount)
  356. {
  357. return itemsPerPage == -1 ? maxItemCount ?? itemsPerPage : Math.Min(maxItemCount ?? itemsPerPage, itemsPerPage);
  358. }
  359. private QueryRequestOptions GetDefaultQueryRequestOptions(int? itemsPerPage = null,
  360. int? maxBufferedItemCount = null,
  361. int? maxConcurrency = null)
  362. {
  363. QueryRequestOptions queryRequestOptions = new QueryRequestOptions
  364. {
  365. MaxItemCount = itemsPerPage == -1 ? 1000 : itemsPerPage,
  366. MaxBufferedItemCount = maxBufferedItemCount ?? 100,
  367. MaxConcurrency = maxConcurrency ?? 50
  368. };
  369. return queryRequestOptions;
  370. }
  371. private async Task<List<T>> ResultsFromQueryAndOptions<T>(CosmosDbQuery cosmosDbQuery, Func<List<T>, Task> batchAction, QueryRequestOptions queryOptions)
  372. {
  373. Container container = await InitializeCollection<T>();
  374. FeedIterator<T> query = container.GetItemQueryIterator<T>(
  375. queryDefinition: cosmosDbQuery.CosmosQueryDefinition,
  376. requestOptions: queryOptions);
  377. return await ResultsFromFeedIterator(query, batchAction, queryOptions.MaxItemCount ?? 0);
  378. }
  379. private QueryRequestOptions GetQueryRequestOptions(int itemsPerPage)
  380. {
  381. QueryRequestOptions queryRequestOptions = new QueryRequestOptions
  382. {
  383. MaxItemCount = itemsPerPage
  384. };
  385. return queryRequestOptions;
  386. }
  387. public async Task<List<T>> FindLinq<T>(Expression<Func<T, bool>> query = null, Expression<Func<T, object>> order = null, bool isDesc = false, int itemsPerPage = -1, int? maxItemCount = null) where T : ID
  388. {
  389. //QueryRequestOptions queryRequestOptions = GetQueryRequestOptions(itemsPerPage);
  390. QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(itemsPerPage, maxItemCount));
  391. FeedIterator<T> feedIterator;
  392. Container container = await InitializeCollection<T>();
  393. if (query == null)
  394. {
  395. if (order != null)
  396. {
  397. if (isDesc)
  398. {
  399. feedIterator = container
  400. .GetItemLinqQueryable<T>(requestOptions: queryRequestOptions).OrderByDescending(order)
  401. .ToFeedIterator();
  402. }
  403. else
  404. {
  405. feedIterator = container
  406. .GetItemLinqQueryable<T>(requestOptions: queryRequestOptions).OrderBy(order)
  407. .ToFeedIterator();
  408. }
  409. }
  410. else
  411. {
  412. feedIterator = container
  413. .GetItemLinqQueryable<T>(requestOptions: queryRequestOptions)
  414. .ToFeedIterator();
  415. }
  416. }
  417. else
  418. {
  419. if (order != null)
  420. {
  421. if (isDesc)
  422. {
  423. feedIterator = container
  424. .GetItemLinqQueryable<T>(requestOptions: queryRequestOptions)
  425. .Where(query).OrderByDescending(order)
  426. .ToFeedIterator();
  427. }
  428. else
  429. {
  430. feedIterator = container
  431. .GetItemLinqQueryable<T>(requestOptions: queryRequestOptions)
  432. .Where(query).OrderBy(order)
  433. .ToFeedIterator();
  434. }
  435. }
  436. else
  437. {
  438. feedIterator = container
  439. .GetItemLinqQueryable<T>(requestOptions: queryRequestOptions)
  440. .Where(query)
  441. .ToFeedIterator();
  442. }
  443. }
  444. return await ResultsFromFeedIterator<T>(feedIterator);
  445. }
  446. public async Task<List<T>> FindSQL<T>(string sql, Dictionary<string, object> Parameters = null, int itemsPerPage = -1, int? maxItemCount = null) where T : ID
  447. {
  448. Container container = await InitializeCollection<T>();
  449. QueryRequestOptions queryOptions = GetQueryRequestOptions(GetEffectivePageSize(itemsPerPage, maxItemCount));
  450. if (Parameters != null)
  451. {
  452. CosmosDbQuery cosmosDbQuery = new CosmosDbQuery
  453. {
  454. QueryText = sql,
  455. Parameters = Parameters
  456. };
  457. FeedIterator<T> feedIterator = container
  458. .GetItemQueryIterator<T>(cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryOptions);
  459. return await ResultsFromFeedIterator(feedIterator);
  460. }
  461. else
  462. {
  463. QueryDefinition queryDefinition = new QueryDefinition(sql);
  464. return await ResultsFromFeedIterator<T>(container.GetItemQueryIterator<T>(queryDefinition));
  465. }
  466. }
  467. //public async Task<List<T>> FindSQL<T>(string sql, bool isPK) where T : ID
  468. //{
  469. // Container container = await InitializeCollection<T>();
  470. // QueryDefinition queryDefinition = new QueryDefinition(sql);
  471. // return await ResultsFromFeedIterator<T>(container.GetItemQueryIterator<T>(queryDefinition));
  472. //}
  473. public async Task<T> ReplaceObject<T>(T entity) where T : ID
  474. {
  475. Container container = await InitializeCollection<T>();
  476. ItemResponse<T> response = await container.ReplaceItemAsync(item: entity, id: entity.id);
  477. if (response.StatusCode.Equals(HttpStatusCode.OK))
  478. {
  479. return response.Resource;
  480. }
  481. else { throw new BizException("error"); }
  482. }
  483. //public async Task<T> ReplaceObject<T>(T entity, string key, string partitionKey) where T : ID
  484. //{
  485. // Container container = await InitializeCollection<T>();
  486. // ItemResponse<T> response = await container.ReplaceItemAsync(item: entity, id: entity.id);
  487. // if (response.StatusCode.Equals(HttpStatusCode.OK))
  488. // {
  489. // return response.Resource;
  490. // }
  491. // else { throw new BizException("error"); }
  492. //}
  493. public async Task<T> Save<T>(T entity) where T : ID
  494. {
  495. try
  496. {
  497. Container container = await InitializeCollection<T>();
  498. ItemResponse<T> response = await container.CreateItemAsync<T>(entity);
  499. return response.Resource;
  500. }
  501. catch (Exception e)
  502. {
  503. throw new BizException(e.Message);
  504. }
  505. }
  506. public async Task<List<T>> SaveAll<T>(List<T> enyites) where T : ID
  507. {
  508. await Task.Run(() => Parallel.ForEach(enyites, (item) =>
  509. {
  510. Task.WaitAll(Save(item));
  511. }));
  512. return enyites;
  513. }
  514. public async Task<T> Update<T>(T entity) where T : ID
  515. {
  516. Container container = await InitializeCollection<T>();
  517. ItemResponse<T> response = await container.UpsertItemAsync(entity);
  518. return response.Resource;
  519. }
  520. public async Task<List<T>> UpdateAll<T>(List<T> entities) where T : ID
  521. {
  522. await Task.Run(() => Parallel.ForEach(entities, (item) =>
  523. {
  524. Task.WaitAll(Update(item));
  525. }));
  526. return entities;
  527. }
  528. public void Dispose()
  529. {
  530. Dispose(true);
  531. }
  532. protected virtual void Dispose(bool disposing)
  533. {
  534. if (disposing)
  535. {
  536. CosmosClient?.Dispose();
  537. }
  538. }
  539. public async Task<T> FindById<T>(string id) where T : ID
  540. {
  541. Container container = await InitializeCollection<T>();
  542. CosmosDbQuery cosmosDbQuery = new CosmosDbQuery
  543. {
  544. QueryText = @"SELECT *
  545. FROM c
  546. WHERE c.id = @id",
  547. Parameters = new Dictionary<string, object>
  548. {
  549. { "@id",id}
  550. }
  551. };
  552. FeedIterator<T> feedIterator = container
  553. .GetItemQueryIterator<T>(cosmosDbQuery.CosmosQueryDefinition);
  554. return (await ResultsFromFeedIterator(feedIterator)).SingleOrDefault();
  555. }
  556. public async Task<T> FindByIdPk<T>(string id, string pk) where T : ID
  557. {
  558. Container container = await InitializeCollection<T>();
  559. ItemResponse<T> response = await container.ReadItemAsync<T>(id: id, partitionKey: new PartitionKey(pk));
  560. return response.Resource;
  561. }
  562. }
  563. }