Client.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Timers;
  6. using InABox.Core;
  7. namespace InABox.Clients
  8. {
  9. public enum SerializerProtocol
  10. {
  11. Rest,
  12. RPC
  13. }
  14. public class QueryMultipleResults
  15. {
  16. private readonly Dictionary<string, CoreTable> Results;
  17. internal QueryMultipleResults(Dictionary<string, CoreTable> results)
  18. {
  19. Results = results;
  20. }
  21. public CoreTable this[string name] => Results[name];
  22. public CoreTable Get<T>() => Results[typeof(T).Name];
  23. /// <summary>
  24. /// Like <see cref="Get{T}"/>, but calls <see cref="CoreTable.ToObjects{T}"/> on the table.
  25. /// </summary>
  26. /// <typeparam name="T"></typeparam>
  27. /// <returns></returns>
  28. public IEnumerable<T> GetObjects<T>()
  29. where T: BaseObject, new()
  30. => Results[typeof(T).Name].ToObjects<T>();
  31. /// <summary>
  32. /// Like <see cref="Get{T}"/>, but calls <see cref="CoreTable.ToArray{T}"/> on the table.
  33. /// </summary>
  34. /// <typeparam name="T"></typeparam>
  35. /// <returns></returns>
  36. public T[] GetArray<T>()
  37. where T: BaseObject, new()
  38. => Results[typeof(T).Name].ToArray<T>();
  39. /// <summary>
  40. /// Like <see cref="Get{T}"/>, but calls <see cref="CoreTable.ToList{T}"/> on the table.
  41. /// </summary>
  42. /// <typeparam name="T"></typeparam>
  43. /// <returns></returns>
  44. public List<T> GetList<T>()
  45. where T: BaseObject, new()
  46. => Results[typeof(T).Name].ToList<T>();
  47. public CoreTable Get(string name) => Results[name];
  48. public CoreTable GetOrDefault(string name) => Results.GetValueOrDefault(name);
  49. }
  50. public abstract class Client
  51. {
  52. public abstract CoreTable Query(IFilter? filter = null, IColumns? columns = null, ISortOrder? sortOrder = null, CoreRange? range = null);
  53. public abstract void Save(Entity entity, string auditNote);
  54. public abstract void Save(IEnumerable<Entity> entity, string auditNote);
  55. private static IClient CheckClient()
  56. {
  57. return ClientFactory.CreateClient<User>();
  58. }
  59. public static Dictionary<string, CoreTable> QueryMultiple(Dictionary<string, IQueryDef> queries)
  60. {
  61. try
  62. {
  63. using var timer = new Profiler(false);
  64. var result = CheckClient().QueryMultiple(queries);
  65. timer.Log(result.Sum(x => x.Value.Rows.Count));
  66. return result;
  67. }
  68. catch (RequestException e)
  69. {
  70. ClientFactory.RaiseRequestError(e);
  71. throw;
  72. }
  73. }
  74. private static IClient<TEntity> CheckClient<TEntity>() where TEntity : Entity, IRemotable, new()
  75. {
  76. return ClientFactory.CreateClient<TEntity>();
  77. }
  78. public static void EnsureColumns<TEntity>(TEntity entity, Columns<TEntity> columns)
  79. where TEntity : Entity, IRemotable, new()
  80. {
  81. var newColumns = Columns.None<TEntity>()
  82. .AddRange(columns.Where(x => !entity.HasColumn(x.Property)));
  83. if (newColumns.Count > 0)
  84. {
  85. var row = Query(new Filter<TEntity>(x => x.ID).IsEqualTo(entity.ID), newColumns).Rows.FirstOrDefault();
  86. row?.FillObject(entity);
  87. }
  88. }
  89. public static void EnsureColumns<TEntity>(ICollection<TEntity> entities, Columns<TEntity> columns)
  90. where TEntity : Entity, IRemotable, new()
  91. {
  92. var newColumns = Columns.None<TEntity>()
  93. .AddRange(columns.Where(x => entities.Any(entity => !entity.HasColumn(x.Property))));
  94. if (newColumns.Count > 0)
  95. {
  96. newColumns.Add(x => x.ID);
  97. var table = Query(new Filter<TEntity>(x => x.ID).InList(entities.Select(x => x.ID).ToArray()), newColumns);
  98. foreach(var row in table.Rows)
  99. {
  100. var id = row.Get<TEntity, Guid>(x => x.ID);
  101. var entity = entities.FirstOrDefault(x => x.ID == id);
  102. if(entity is null)
  103. {
  104. // Shouldn't happen, but just in case.
  105. continue;
  106. }
  107. row?.FillObject(entity);
  108. }
  109. }
  110. }
  111. public static CoreTable Query<TEntity>(Filter<TEntity>? filter = null, Columns<TEntity>? columns = null, SortOrder<TEntity>? orderby = null, CoreRange? range = null)
  112. where TEntity : Entity, IRemotable, new()
  113. {
  114. return new Client<TEntity>().Query(filter, columns, orderby, range);
  115. }
  116. public static void Query<TEntity>(Filter<TEntity>? filter, Columns<TEntity>? columns, SortOrder<TEntity>? orderby, CoreRange? range, Action<CoreTable?, Exception?> callback)
  117. where TEntity : Entity, IRemotable, new()
  118. {
  119. new Client<TEntity>().Query(filter, columns, orderby, range, callback);
  120. }
  121. public static void Query<TEntity>(Filter<TEntity>? filter, Columns<TEntity>? columns, SortOrder<TEntity>? orderby, Action<CoreTable?, Exception?> callback)
  122. where TEntity : Entity, IRemotable, new()
  123. {
  124. new Client<TEntity>().Query(filter, columns, orderby, null, callback);
  125. }
  126. public static void Save<TEntity>(TEntity entity, string auditNote)
  127. where TEntity : Entity, IRemotable, new()
  128. {
  129. new Client<TEntity>().Save(entity, auditNote);
  130. }
  131. public static void Save<TEntity>(IEnumerable<TEntity> entities, string auditNote)
  132. where TEntity : Entity, IRemotable, new()
  133. {
  134. new Client<TEntity>().Save(entities, auditNote);
  135. }
  136. public static void Save<TEntity>(TEntity entity, string auditNote, Action<TEntity, Exception?> callback)
  137. where TEntity : Entity, IRemotable, new()
  138. {
  139. new Client<TEntity>().Save(entity, auditNote, callback);
  140. }
  141. public static void Save<TEntity>(IEnumerable<TEntity> entities, string auditNote, Action<IEnumerable<TEntity>, Exception?> callback)
  142. where TEntity : Entity, IRemotable, new()
  143. {
  144. new Client<TEntity>().Save(entities, auditNote, callback);
  145. }
  146. public static void Delete<TEntity>(TEntity entity, string auditNote)
  147. where TEntity : Entity, IRemotable, new()
  148. {
  149. new Client<TEntity>().Delete(entity, auditNote);
  150. }
  151. public static void Delete<TEntity>(TEntity entity, string auditNote, Action<TEntity, Exception?> callback)
  152. where TEntity : Entity, IRemotable, new()
  153. {
  154. new Client<TEntity>().Delete(entity, auditNote, callback);
  155. }
  156. public static void Delete<TEntity>(IEnumerable<TEntity> entities, string auditNote)
  157. where TEntity : Entity, IRemotable, new()
  158. {
  159. new Client<TEntity>().Delete(entities, auditNote);
  160. }
  161. public static void QueryMultiple(
  162. Action<Dictionary<string, CoreTable>?, Exception?> callback,
  163. Dictionary<string, IQueryDef> queries)
  164. {
  165. try
  166. {
  167. using var timer = new Profiler(false);
  168. CheckClient().QueryMultiple((result, e) =>
  169. {
  170. timer.Dispose(result != null ? result.Sum(x => x.Value.Rows.Count) : -1);
  171. callback?.Invoke(result, e);
  172. }, queries);
  173. }
  174. catch (RequestException e)
  175. {
  176. ClientFactory.RaiseRequestError(e);
  177. throw;
  178. }
  179. }
  180. public static QueryMultipleResults QueryMultiple(params IKeyedQueryDef[] queries) =>
  181. new QueryMultipleResults(QueryMultiple(queries.ToDictionary(x => x.Key, x => x as IQueryDef)));
  182. public static void QueryMultiple(Action<QueryMultipleResults?, Exception?> callback, params IKeyedQueryDef[] queries) =>
  183. QueryMultiple((results, e) =>
  184. {
  185. if (results != null)
  186. {
  187. callback?.Invoke(new QueryMultipleResults(results), e);
  188. }
  189. else
  190. {
  191. callback?.Invoke(null, e);
  192. }
  193. }, queries.ToDictionary(x => x.Key, x => x as IQueryDef));
  194. public static QueryMultipleResults QueryMultiple(IEnumerable<IKeyedQueryDef> queries) =>
  195. new QueryMultipleResults(QueryMultiple(queries.ToDictionary(x => x.Key, x => x as IQueryDef)));
  196. public static void QueryMultiple(Action<QueryMultipleResults?, Exception?> callback, IEnumerable<IKeyedQueryDef> queries) =>
  197. QueryMultiple((results, e) =>
  198. {
  199. if(results != null)
  200. {
  201. callback?.Invoke(new QueryMultipleResults(results), e);
  202. }
  203. else
  204. {
  205. callback?.Invoke(null, e);
  206. }
  207. }, queries.ToDictionary(x => x.Key, x => x as IQueryDef));
  208. public static IValidationData Validate(Guid session)
  209. {
  210. try
  211. {
  212. using (new Profiler(true))
  213. return CheckClient().Validate(session);
  214. }
  215. catch (RequestException e)
  216. {
  217. ClientFactory.RaiseRequestError(e);
  218. throw;
  219. }
  220. }
  221. public static IValidationData Validate(string pin, Guid session = default)
  222. {
  223. try
  224. {
  225. using (new Profiler(true))
  226. return CheckClient().Validate(pin, session);
  227. }
  228. catch (RequestException e)
  229. {
  230. ClientFactory.RaiseRequestError(e);
  231. throw;
  232. }
  233. }
  234. public static IValidationData Validate(string userid, string password, Guid session = default)
  235. {
  236. try
  237. {
  238. using (new Profiler(true))
  239. return CheckClient().Validate(userid, password, session);
  240. }
  241. catch (RequestException e)
  242. {
  243. ClientFactory.RaiseRequestError(e);
  244. throw;
  245. }
  246. }
  247. public static bool Check2FA(string code, Guid? session = null)
  248. {
  249. try
  250. {
  251. using (new Profiler(true))
  252. return CheckClient().Check2FA(code, session);
  253. }
  254. catch (RequestException e)
  255. {
  256. ClientFactory.RaiseRequestError(e);
  257. throw;
  258. }
  259. }
  260. public static bool Ping()
  261. {
  262. try
  263. {
  264. return CheckClient().Ping();
  265. }
  266. catch (RequestException e)
  267. {
  268. ClientFactory.RaiseRequestError(e);
  269. throw;
  270. }
  271. }
  272. public static DatabaseInfo? Info()
  273. {
  274. try
  275. {
  276. using (new Profiler(true))
  277. return CheckClient().Info();
  278. }
  279. catch (RequestException e)
  280. {
  281. ClientFactory.RaiseRequestError(e);
  282. throw;
  283. }
  284. }
  285. public static string Version()
  286. {
  287. try
  288. {
  289. using (new Profiler(true))
  290. return CheckClient().Version();
  291. }
  292. catch (RequestException e)
  293. {
  294. ClientFactory.RaiseRequestError(e);
  295. throw;
  296. }
  297. }
  298. public static string ReleaseNotes()
  299. {
  300. try
  301. {
  302. using (new Profiler(true))
  303. return CheckClient().ReleaseNotes();
  304. }
  305. catch (RequestException e)
  306. {
  307. ClientFactory.RaiseRequestError(e);
  308. throw;
  309. }
  310. }
  311. public static byte[]? Installer()
  312. {
  313. try
  314. {
  315. using (new Profiler(true))
  316. return CheckClient().Installer();
  317. }
  318. catch (RequestException e)
  319. {
  320. ClientFactory.RaiseRequestError(e);
  321. throw;
  322. }
  323. }
  324. public static Client Create(Type TEntity) =>
  325. (Activator.CreateInstance(typeof(Client<>).MakeGenericType(TEntity)) as Client)!;
  326. }
  327. public class Client<TEntity> : Client, IDisposable where TEntity : Entity, IRemotable, new()
  328. {
  329. #region IQueryProvider
  330. private class ClientQueryProvider : IQueryProvider<TEntity>
  331. {
  332. public CoreTable Query(Filter<TEntity>? filter = null, Columns<TEntity>? columns = null, SortOrder<TEntity>? sort = null, CoreRange? range = null)
  333. {
  334. return Client.Query(filter, columns, sort, range);
  335. }
  336. }
  337. public static IQueryProvider<TEntity> Provider { get; private set; } = new ClientQueryProvider();
  338. #endregion
  339. private IClient<TEntity> _client;
  340. public Client()
  341. {
  342. _client = ClientFactory.CreateClient<TEntity>();
  343. }
  344. public void Dispose()
  345. {
  346. }
  347. private void CheckSupported()
  348. {
  349. if (!ClientFactory.IsSupported<TEntity>())
  350. throw new NotSupportedException(string.Format("{0} is not supported in this context", typeof(TEntity).EntityName()));
  351. }
  352. public CoreTable Query(Filter<TEntity>? filter = null, Columns<TEntity>? columns = null, SortOrder<TEntity>? orderby = null, CoreRange? range = null)
  353. {
  354. try
  355. {
  356. using var timer = new Profiler<TEntity>(false);
  357. CheckSupported();
  358. var result = _client.Query(filter, columns, orderby, range);
  359. timer.Log(result.Rows.Count);
  360. return result;
  361. }
  362. catch(RequestException e)
  363. {
  364. ClientFactory.RaiseRequestError(e);
  365. throw;
  366. }
  367. }
  368. public override CoreTable Query(IFilter? filter = null, IColumns? columns = null, ISortOrder? sortOrder = null, CoreRange? range = null)
  369. {
  370. return Query(filter as Filter<TEntity>, columns as Columns<TEntity>, sortOrder as SortOrder<TEntity>, range);
  371. }
  372. public void Query(Filter<TEntity>? filter, Columns<TEntity>? columns, SortOrder<TEntity>? sort, CoreRange? range, Action<CoreTable?, Exception?>? callback)
  373. {
  374. try
  375. {
  376. var timer = new Profiler<TEntity>(false);
  377. CheckSupported();
  378. _client.Query(filter, columns, sort, range, (c, e) =>
  379. {
  380. timer.Log(c != null ? c.Rows.Count : -1);
  381. callback?.Invoke(c, e);
  382. });
  383. }
  384. catch (RequestException e)
  385. {
  386. ClientFactory.RaiseRequestError(e);
  387. throw;
  388. }
  389. }
  390. public TEntity[] Load(Filter<TEntity>? filter = null, SortOrder<TEntity>? sort = null, CoreRange? range = null)
  391. {
  392. try
  393. {
  394. using (var timer = new Profiler<TEntity>(false))
  395. {
  396. CheckSupported();
  397. var result = _client.Load(filter, sort, range);
  398. foreach (var entity in result)
  399. entity.CommitChanges();
  400. timer.Log(result.Length);
  401. return result;
  402. }
  403. }
  404. catch (RequestException e)
  405. {
  406. ClientFactory.RaiseRequestError(e);
  407. throw;
  408. }
  409. }
  410. public void Load(Filter<TEntity> filter, SortOrder<TEntity> sort, CoreRange? range, Action<TEntity[]?, Exception?>? callback)
  411. {
  412. try
  413. {
  414. var timer = new Profiler<TEntity>(false);
  415. CheckSupported();
  416. _client.Load(filter, sort, range,(i, e) =>
  417. {
  418. timer.Dispose(i != null ? i.Length : -1);
  419. callback?.Invoke(i, e);
  420. });
  421. }
  422. catch (RequestException e)
  423. {
  424. ClientFactory.RaiseRequestError(e);
  425. throw;
  426. }
  427. }
  428. public override void Save(Entity entity, string auditNote)
  429. {
  430. try
  431. {
  432. Save((entity as TEntity)!, auditNote);
  433. }
  434. catch (RequestException e)
  435. {
  436. ClientFactory.RaiseRequestError(e);
  437. throw;
  438. }
  439. }
  440. public override void Save(IEnumerable<Entity> entities, string auditNote)
  441. {
  442. try
  443. {
  444. Save(entities.Cast<TEntity>(), auditNote);
  445. }
  446. catch (RequestException e)
  447. {
  448. ClientFactory.RaiseRequestError(e);
  449. throw;
  450. }
  451. }
  452. public void Save(TEntity entity, string auditnote)
  453. {
  454. try
  455. {
  456. using (new Profiler<TEntity>(true))
  457. {
  458. CheckSupported();
  459. entity.LastUpdate = DateTime.Now;
  460. entity.LastUpdateBy = ClientFactory.UserID;
  461. _client.Save(entity, auditnote);
  462. entity.CommitChanges();
  463. }
  464. }
  465. catch (RequestException e)
  466. {
  467. ClientFactory.RaiseRequestError(e);
  468. throw;
  469. }
  470. }
  471. public void Save(TEntity entity, string auditnote, Action<TEntity, Exception?> callback)
  472. {
  473. try
  474. {
  475. var timer = new Profiler<TEntity>(false);
  476. CheckSupported();
  477. _client.Save(entity, auditnote, (i, c) =>
  478. {
  479. timer.Dispose();
  480. callback?.Invoke(i, c);
  481. });
  482. }
  483. catch (RequestException e)
  484. {
  485. ClientFactory.RaiseRequestError(e);
  486. throw;
  487. }
  488. }
  489. public void Save(IEnumerable<TEntity> entities, string auditnote)
  490. {
  491. try
  492. {
  493. using var timer = new Profiler<TEntity>(false);
  494. CheckSupported();
  495. var items = entities.AsArray();
  496. if (items.Any())
  497. _client.Save(items, auditnote);
  498. timer.Log(items.Length);
  499. }
  500. catch (RequestException e)
  501. {
  502. ClientFactory.RaiseRequestError(e);
  503. throw;
  504. }
  505. }
  506. public void Save(IEnumerable<TEntity> entities, string auditnote, Action<IEnumerable<TEntity>, Exception?> callback)
  507. {
  508. try
  509. {
  510. var timer = new Profiler<TEntity>(false);
  511. CheckSupported();
  512. var items = entities.AsArray();
  513. if (items.Any())
  514. {
  515. _client.Save(items, auditnote, (i, e) =>
  516. {
  517. timer.Dispose(i.Count());
  518. callback?.Invoke(i, e);
  519. });
  520. }
  521. else
  522. {
  523. timer.Dispose(0);
  524. callback?.Invoke(items, null);
  525. }
  526. }
  527. catch (RequestException e)
  528. {
  529. ClientFactory.RaiseRequestError(e);
  530. throw;
  531. }
  532. }
  533. public void Delete(TEntity entity, string auditnote)
  534. {
  535. try
  536. {
  537. using (new Profiler<TEntity>(true))
  538. {
  539. CheckSupported();
  540. _client.Delete(entity, auditnote);
  541. }
  542. }
  543. catch (RequestException e)
  544. {
  545. ClientFactory.RaiseRequestError(e);
  546. throw;
  547. }
  548. }
  549. public void Delete(TEntity entity, string auditnote, Action<TEntity, Exception?> callback)
  550. {
  551. try
  552. {
  553. var timer = new Profiler<TEntity>(true);
  554. CheckSupported();
  555. _client.Delete(entity, auditnote, (i, e) =>
  556. {
  557. timer.Dispose();
  558. callback?.Invoke(i, e);
  559. });
  560. }
  561. catch (RequestException e)
  562. {
  563. ClientFactory.RaiseRequestError(e);
  564. throw;
  565. }
  566. }
  567. public void Delete(IEnumerable<TEntity> entities, string auditnote)
  568. {
  569. try
  570. {
  571. using var timer = new Profiler<TEntity>(false);
  572. CheckSupported();
  573. var items = entities.AsArray();
  574. _client.Delete(items, auditnote);
  575. timer.Log(items.Length);
  576. }
  577. catch (RequestException e)
  578. {
  579. ClientFactory.RaiseRequestError(e);
  580. throw;
  581. }
  582. }
  583. public void Delete(IEnumerable<TEntity> entities, string auditnote, Action<IList<TEntity>, Exception?> callback)
  584. {
  585. try
  586. {
  587. var timer = new Profiler<TEntity>(false);
  588. CheckSupported();
  589. var items = entities.AsArray();
  590. _client.Delete(items, auditnote, (i, e) =>
  591. {
  592. timer.Dispose(i.Count);
  593. callback?.Invoke(i, e);
  594. });
  595. }
  596. catch (RequestException e)
  597. {
  598. ClientFactory.RaiseRequestError(e);
  599. throw;
  600. }
  601. }
  602. public IEnumerable<string> SupportedTypes()
  603. {
  604. try
  605. {
  606. using (new Profiler(true))
  607. return _client.SupportedTypes();
  608. }
  609. catch (RequestException e)
  610. {
  611. ClientFactory.RaiseRequestError(e);
  612. throw;
  613. }
  614. }
  615. public new DatabaseInfo Info()
  616. {
  617. try
  618. {
  619. using (new Profiler(true))
  620. return _client.Info();
  621. }
  622. catch (RequestException e)
  623. {
  624. ClientFactory.RaiseRequestError(e);
  625. throw;
  626. }
  627. }
  628. }
  629. public static class ClientExtensions
  630. {
  631. /// <summary>
  632. /// Load the properties of any <see cref="EntityLink{T}"/>s on this <typeparamref name="T"/> where the <see cref="IEntityLink.ID"/> is not <see cref="Guid.Empty"/>.
  633. /// This allows us to populate columns of transient objects, as long as they are linked by the ID. What this actually then does is query each
  634. /// linked table with the required columns.
  635. /// </summary>
  636. /// <param name="columns"></param>
  637. public static void LoadForeignProperties<T>(this IEnumerable<T> items, Columns<T> columns)
  638. where T : BaseObject, new()
  639. {
  640. // Lists of properties that we need, arranged by the entity link property which is their parent.
  641. // LinkIDProperty : (Type, Properties: [(columnName, property)], Objects)
  642. var newData = new Dictionary<IProperty, Tuple<Type, List<Tuple<string, IProperty>>, HashSet<T>>>();
  643. foreach (var column in columns)
  644. {
  645. var property = DatabaseSchema.Property(typeof(T), column.Property);
  646. if (property?.GetOuterParent(x => x.IsEntityLink) is IProperty linkProperty)
  647. {
  648. var remaining = column.Property[(linkProperty.Name.Length + 1)..];
  649. if (remaining.Equals(nameof(IEntityLink.ID)))
  650. {
  651. // This guy isn't foreign, so we don't pull him.
  652. continue;
  653. }
  654. var idProperty = DatabaseSchema.Property(typeof(T), linkProperty.Name + "." + nameof(IEntityLink.ID))!;
  655. var linkType = linkProperty.PropertyType.GetInterfaceDefinition(typeof(IEntityLink<>))!.GenericTypeArguments[0];
  656. if (!newData.TryGetValue(idProperty, out var data))
  657. {
  658. data = new Tuple<Type, List<Tuple<string, IProperty>>, HashSet<T>>(
  659. linkType,
  660. new List<Tuple<string, IProperty>>(),
  661. new HashSet<T>());
  662. newData.Add(idProperty, data);
  663. }
  664. var any = false;
  665. foreach (var item in items)
  666. {
  667. if (!item.LoadedColumns.Contains(column.Property))
  668. {
  669. var linkID = (Guid)idProperty.Getter()(item);
  670. if (linkID != Guid.Empty)
  671. {
  672. any = true;
  673. data.Item3.Add(item);
  674. }
  675. }
  676. }
  677. if (any)
  678. {
  679. data.Item2.Add(new Tuple<string, IProperty>(remaining, property));
  680. }
  681. }
  682. }
  683. var queryDefs = new List<IKeyedQueryDef>();
  684. foreach (var (prop, data) in newData)
  685. {
  686. if (data.Item2.Count != 0)
  687. {
  688. var ids = data.Item3.Select(prop.Getter()).Cast<Guid>().ToArray();
  689. queryDefs.Add(new KeyedQueryDef(prop.Name, data.Item1,
  690. Filter.Create<Entity>(data.Item1, x => x.ID).InList(ids),
  691. Columns.None(data.Item1)
  692. .Add(data.Item2.Select(x => x.Item1))
  693. .Add<Entity>(x => x.ID)));
  694. }
  695. }
  696. var results = Client.QueryMultiple(queryDefs);
  697. foreach(var (prop, data) in newData)
  698. {
  699. var table = results.GetOrDefault(prop.Name);
  700. if(table is null)
  701. {
  702. continue;
  703. }
  704. var keyCol = table.GetColumnIndex<Entity, Guid>(x => x.ID);
  705. var dict = table.Rows.ToDictionary(x => x.Get<Guid>(keyCol));
  706. foreach (var entity in data.Item3)
  707. {
  708. var linkID = (Guid)prop.Getter()(entity);
  709. if (dict.TryGetValue(linkID, out var row))
  710. {
  711. foreach (var (name, property) in data.Item2)
  712. {
  713. if (!entity.LoadedColumns.Contains(property.Name))
  714. {
  715. property.Setter()(entity, row[name]);
  716. entity.LoadedColumns.Add(property.Name);
  717. }
  718. }
  719. }
  720. }
  721. }
  722. }
  723. }
  724. }