AzureCosmosDBV3Repository.cs 26 KB

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