DataModel.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Linq;
  6. using System.Linq.Expressions;
  7. using System.Reflection;
  8. using InABox.Clients;
  9. namespace InABox.Core
  10. {
  11. public delegate void DataModelUpdateEvent(string section, DataModel model);
  12. [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
  13. public sealed class DataModelTableNameAttribute : Attribute
  14. {
  15. public string TableName { get; set; }
  16. public DataModelTableNameAttribute(string tableName)
  17. {
  18. TableName = tableName;
  19. }
  20. }
  21. public interface IDataModelSource
  22. {
  23. string SectionName { get; }
  24. DataModel DataModel(Selection selection);
  25. event DataModelUpdateEvent? OnUpdateDataModel;
  26. }
  27. public interface IDataModelRelationship
  28. {
  29. string ChildColumn { get; }
  30. string ChildTable { get; }
  31. string ParentColumn { get; }
  32. string ParentTable { get; }
  33. bool IsLookup { get; }
  34. DataRelation AsDataRelation();
  35. string ParentColumnAsPropertyName();
  36. string ChildColumnAsPropertyName();
  37. }
  38. public interface IDataModelQueryDef : IQueryDef
  39. {
  40. string TableName { get; }
  41. }
  42. public class DataModelQueryDef<T> : IDataModelQueryDef
  43. {
  44. public DataModelQueryDef(Filter<T> filter, Columns<T> columns, SortOrder<T> sortorder, string? alias = null)
  45. {
  46. Type = typeof(T);
  47. Filter = filter;
  48. Columns = columns;
  49. SortOrder = sortorder;
  50. TableName = DataModel.TableName(Type, alias);
  51. }
  52. public Type Type { get; }
  53. public IFilter Filter { get; }
  54. public IColumns Columns { get; }
  55. public ISortOrder SortOrder { get; }
  56. public string TableName { get; }
  57. }
  58. public delegate void OnBeforeLoad(CancelEventArgs args);
  59. public delegate void OnAfterLoad(CancelEventArgs args);
  60. public interface IDataModel
  61. {
  62. IEnumerable<DataTable> DefaultTables { get; }
  63. void AddTable(Type type, CoreTable table, bool isdefault = false, string? alias = null);
  64. /// <summary>
  65. /// Adds a table to the datamodel.
  66. /// </summary>
  67. /// <typeparam name="TType">The type of the object represented by the table.</typeparam>
  68. /// <param name="filter">A filter for the table. If set to <see langword="null"/>, loads all objects of <typeparamref name="TType"/>.</param>
  69. /// <param name="columns">The columns to load for this table. If set to <see langword="null"/>, loads all the columns of <typeparamref name="TType"/>.</param>
  70. /// <param name="isdefault">
  71. /// Is this table default loaded? If set to <see langword="true"/>, this table is added to <see cref="DefaultTables"/>.</param>
  72. /// <param name="alias">The name of this table. Defaults to <typeparamref name="TType"/> if not set or <see langword="null"/>.</param>
  73. /// <param name="shouldLoad">
  74. /// <see langword="true"/> if this table should be loaded - in some cases a table's data should loaded manually.<br/>
  75. /// Set to <see langword="false"/> if this is the case.
  76. /// </param>
  77. void AddTable<TType>(Filter<TType>? filter, Columns<TType>? columns, bool isdefault = false, string? alias = null, bool shouldLoad = true);
  78. void LinkTable(Type parenttype, string parentcolumn, Type childtype, string childcolumn, string? parentalias = null, string? childalias = null, bool isLookup = false);
  79. void LinkTable<TParent, TChild>(Expression<Func<TParent, object>> parent, Expression<Func<TChild, object>> child, string? parentalias = null,
  80. string? childalias = null, bool isLookup = false);
  81. void AddChildTable<TParent, TChild>(Expression<Func<TParent, object>> parentcolumn, Expression<Func<TChild, object>> childcolumn,
  82. Filter<TChild>? filter = null, Columns<TChild>? columns = null, bool isdefault = false, string? parentalias = null,
  83. string? childalias = null);
  84. void AddLookupTable<TSource, TLookup>(Expression<Func<TSource, object>> sourcecolumn, Expression<Func<TLookup, object>> lookupcolumn,
  85. Filter<TLookup>? filter = null, Columns<TLookup>? columns = null, bool isdefault = false, string? sourcealias = null,
  86. string? lookupalias = null);
  87. /// <summary>
  88. /// Remove a table from the data model.
  89. /// </summary>
  90. /// <typeparam name="TType">The type of the table to be removed.</typeparam>
  91. /// <param name="alias">The table name, defaulting to the name of <typeparamref name="TType"/>.</param>
  92. /// <returns><see langword="true"/> if the table was removed, <see langword="false"/> if it was not removed because it didn't exist.</returns>
  93. bool RemoveTable<TType>(string? alias = null);
  94. /// <summary>
  95. /// Gets the filter for a given table, which is used during <see cref="LoadModel(IEnumerable{string}, IDataModelQueryDef[]).
  96. /// </summary>
  97. /// <typeparam name="TType">The type of the table to get the filter of.</typeparam>
  98. /// <param name="alias">The name of the table, defaulting to <typeparamref name="TType"/></param>
  99. /// <returns>The filter.</returns>
  100. Filter<TType>? GetFilter<TType>(string? alias = null);
  101. /// <summary>
  102. /// Gets the columns for a given table, which are used during <see cref="LoadModel(IEnumerable{string}, IDataModelQueryDef[]).
  103. /// </summary>
  104. /// <typeparam name="TType">The type of the table to get the columns of.</typeparam>
  105. /// <param name="alias">The name of the table, defaulting to <typeparamref name="TType"/></param>
  106. /// <returns>The columns.</returns>
  107. Columns<TType>? GetColumns<TType>(string? alias = null);
  108. /// <summary>
  109. /// Sets the filter for a given table, which is used during <see cref="LoadModel(IEnumerable{string}, IDataModelQueryDef[]).
  110. /// </summary>
  111. /// <typeparam name="TType">The type of the table to set the filter of.</typeparam>
  112. /// <param name="filter">The new filter.</param>
  113. /// <param name="alias">The name of the table, defaulting to <typeparamref name="TType"/></param>
  114. void SetFilter<TType>(Filter<TType>? filter, string? alias = null);
  115. /// <summary>
  116. /// Sets the columns for a given table, which are used during <see cref="LoadModel(IEnumerable{string}, IDataModelQueryDef[]).
  117. /// </summary>
  118. /// <typeparam name="TType">The type of the table.</typeparam>
  119. /// <param name="columns">The new columns.</param>
  120. /// <param name="alias">The name of the table, defaulting to <typeparamref name="TType"/>.</param>
  121. void SetColumns<TType>(Columns<TType>? columns, string? alias = null);
  122. void SetIsDefault<TType>(bool isDefault, string? alias = null);
  123. void SetShouldLoad<TType>(bool shouldLoad, string? alias = null);
  124. CoreTable GetTable<TType>(string? alias = null);
  125. void SetTableData(Type type, CoreTable tableData, string? alias = null);
  126. bool HasTable(Type type, string? alias = null);
  127. void LoadModel(IEnumerable<string> requiredTables, Dictionary<string, IQueryDef>? requiredQueries = null);
  128. void LoadModel(IEnumerable<string> requiredTables, params IDataModelQueryDef[] requiredQueries);
  129. TType[] ExtractValues<TSource, TType>(Expression<Func<TSource, TType>> column, bool distinct = true, string? alias = null);
  130. }
  131. public abstract class DataModel : IDataModel
  132. {
  133. private readonly List<IDataModelRelationship> _relationships = new List<IDataModelRelationship>();
  134. private readonly Dictionary<string, DataModelTable> _tables = new Dictionary<string, DataModelTable>();
  135. public DataModel()
  136. {
  137. AddTable<CompanyInformation>(null, null, true);
  138. AddChildTable<CompanyInformation, Document>(x => x.Logo.ID, x => x.ID, null, null, true, null, "CompanyLogo");
  139. AddTable(new Filter<User>(x => x.ID).IsEqualTo(ClientFactory.UserGuid), null, true);
  140. }
  141. public Dictionary<Type, CoreTable> AsDictionary
  142. {
  143. get
  144. {
  145. var result = new Dictionary<Type, CoreTable>();
  146. foreach (var alias in _tables.Keys)
  147. result[_tables[alias].Type] = _tables[alias].Table;
  148. return result;
  149. }
  150. }
  151. public abstract string Name { get; }
  152. public IEnumerable<DataRelation> Relations => _relationships.Select(x => x.AsDataRelation()).ToArray();
  153. public IEnumerable<DataTable> Tables => _tables.Select(x => x.Value.Table.ToDataTable(x.Key));
  154. public IEnumerable<DataTable> DefaultTables => _tables.Where(x => x.Value.IsDefault).Select(x => x.Value.Table.ToDataTable(x.Key));
  155. public IEnumerable<string> DefaultTableNames => _tables.Where(x => x.Value.IsDefault).Select(x => x.Key);
  156. public TType[] ExtractValues<TSource, TType>(Expression<Func<TSource, TType>> column, bool distinct = true, string? alias = null)
  157. {
  158. return GetTable<TSource>(alias).ExtractValues(column, distinct).ToArray();
  159. }
  160. public DataSet AsDataSet()
  161. {
  162. var result = new DataSet();
  163. result.Tables.AddRange(_tables.Select(x => x.Value.Table.ToDataTable(x.Key)).ToArray());
  164. foreach (var relation in _relationships)
  165. {
  166. var childTable = result.Tables[relation.ChildTable];
  167. var parentTable = result.Tables[relation.ParentTable];
  168. if (childTable is null)
  169. {
  170. continue;
  171. }
  172. if (parentTable is null)
  173. {
  174. result.Tables.Remove(childTable);
  175. continue;
  176. }
  177. var parentColumn = parentTable.Columns[relation.ParentColumn.Replace(".", "_")];
  178. var childColumn = childTable.Columns[relation.ChildColumn.Replace(".", "_")];
  179. if (parentColumn is null || childColumn is null)
  180. {
  181. result.Tables.Remove(childTable);
  182. continue;
  183. }
  184. if (relation.IsLookup)
  185. {
  186. result.Relations.Add(
  187. string.Format("{0}_{1}", relation.ChildTable, relation.ParentTable),
  188. childColumn,
  189. parentColumn,
  190. false
  191. );
  192. }
  193. else
  194. {
  195. result.Relations.Add(
  196. string.Format("{0}_{1}", relation.ParentTable, relation.ChildTable),
  197. parentColumn,
  198. childColumn,
  199. false
  200. );
  201. }
  202. }
  203. return result;
  204. }
  205. public event OnBeforeLoad? OnBeforeLoad;
  206. public event OnAfterLoad? OnAfterLoad;
  207. protected virtual void BeforeLoad(IEnumerable<string> requiredtables)
  208. {
  209. }
  210. protected virtual void CheckRequiredTables(List<string> requiredtables)
  211. {
  212. }
  213. //protected abstract void Load(IEnumerable<string> requiredtables);
  214. protected virtual void AfterLoad(IEnumerable<string> requiredTables)
  215. {
  216. }
  217. protected void Load(Type type, CoreTable data, IEnumerable<string> requiredtables, string? alias = null)
  218. {
  219. CheckTable(type, alias);
  220. var name = TableName(type, alias);
  221. var table = _tables[name].Table;
  222. if(!ReferenceEquals(table, data))
  223. {
  224. table.Rows.Clear();
  225. if (IsRequired(type, requiredtables, alias))
  226. data.CopyTo(table);
  227. }
  228. }
  229. protected void Load<TType>(CoreTable data, IEnumerable<string> requiredtables, string? alias = null)
  230. {
  231. Load(typeof(TType), data, requiredtables, alias);
  232. }
  233. protected void Load<TType>(IEnumerable<TType> items, IEnumerable<string> requiredtables, string? alias = null)
  234. where TType : notnull
  235. {
  236. CheckTable<TType>(alias);
  237. var name = TableName<TType>(alias);
  238. var table = _tables[name].Table;
  239. table.Rows.Clear();
  240. if (IsRequired<TType>(requiredtables))
  241. foreach (var item in items)
  242. {
  243. var row = table.NewRow();
  244. table.LoadRow(row, item);
  245. table.Rows.Add(row);
  246. }
  247. }
  248. private void CheckTable<TType>(string? alias = null)
  249. {
  250. CheckTable(typeof(TType), alias);
  251. }
  252. protected string TableName<TType>(string? alias = null)
  253. {
  254. return TableName(typeof(TType), alias);
  255. }
  256. private class DataModelTable
  257. {
  258. public DataModelTable(Type type, CoreTable table, bool isDefault, IFilter? filter, IColumns? columns, bool shouldLoad = true)
  259. {
  260. Type = type;
  261. Table = table;
  262. IsDefault = isDefault;
  263. Filter = filter;
  264. Columns = columns;
  265. ShouldLoad = shouldLoad;
  266. }
  267. public Type Type { get; }
  268. public CoreTable Table { get; set; }
  269. public bool IsDefault { get; set; }
  270. public IFilter? Filter { get; set; }
  271. public IColumns? Columns { get; set; }
  272. public bool ShouldLoad { get; set; }
  273. }
  274. #region New Load Methods
  275. private Filter<TChild> GetSubquery<TParent, TChild>(IDataModelRelationship relation, Dictionary<string, IQueryDef> requiredQueries)
  276. where TParent : Entity, IRemotable, IPersistent, new()
  277. where TChild : Entity, IRemotable, IPersistent, new()
  278. {
  279. var parentFilter = GetTableFilter<TParent>(relation.ParentTable, requiredQueries);
  280. var subQuery = new SubQuery<TParent>(parentFilter, new Column<TParent>(relation.ParentColumnAsPropertyName()));
  281. var filter = new Filter<TChild>();
  282. filter.Expression = CoreUtils.CreateMemberExpression(typeof(TChild), relation.ChildColumnAsPropertyName());
  283. filter.Operator = Operator.InQuery;
  284. filter.Value = subQuery;
  285. return filter;
  286. }
  287. private Filter<TType>? GetTableFilter<TType>(string tableName, Dictionary<string, IQueryDef> requiredQueries)
  288. where TType : Entity, IRemotable, IPersistent, new()
  289. {
  290. var newFilter = _tables[tableName].Filter as Filter<TType>;
  291. IQueryDef? query = null;
  292. requiredQueries?.TryGetValue(tableName, out query);
  293. if (query?.Filter is Filter<TType> filter)
  294. {
  295. if (newFilter != null)
  296. newFilter.And(filter);
  297. else
  298. newFilter = filter;
  299. }
  300. var relation = _relationships.Where(x => x.ChildTable == tableName).FirstOrDefault();
  301. if (relation != null)
  302. {
  303. var subFilter = (typeof(DataModel).GetMethod(nameof(GetSubquery), BindingFlags.NonPublic | BindingFlags.Instance)
  304. .MakeGenericMethod(_tables[relation.ParentTable].Type, typeof(TType))
  305. .Invoke(this, new object?[] { relation, requiredQueries }) as Filter<TType>)!;
  306. if (newFilter != null)
  307. newFilter.And(subFilter);
  308. else
  309. newFilter = subFilter;
  310. }
  311. return newFilter;
  312. }
  313. private IQueryDef LoadModelTable<TType>(string tableName, Dictionary<string, IQueryDef> requiredQueries)
  314. where TType : Entity, IRemotable, IPersistent, new()
  315. {
  316. var newFilter = GetTableFilter<TType>(tableName, requiredQueries);
  317. var newColumns = _tables[tableName].Columns as Columns<TType>;
  318. IQueryDef? query = null;
  319. requiredQueries?.TryGetValue(tableName, out query);
  320. if (query == null) return new QueryDef<TType>(newFilter, newColumns, null);
  321. if (query.Columns != null) newColumns = query.Columns as Columns<TType>;
  322. return new QueryDef<TType>(
  323. newFilter,
  324. newColumns,
  325. query.SortOrder as SortOrder<TType>
  326. );
  327. }
  328. public virtual void LoadModel(IEnumerable<string>? requiredTables, Dictionary<string, IQueryDef>? requiredQueries = null)
  329. {
  330. var requiredTablesList = requiredTables != null ? requiredTables.ToList() : new List<string>();
  331. CheckRequiredTables(requiredTablesList);
  332. var args = new CancelEventArgs();
  333. OnBeforeLoad?.Invoke(args);
  334. if (!args.Cancel) BeforeLoad(requiredTablesList);
  335. var queries = new Dictionary<string, IQueryDef>();
  336. var genericMethod = typeof(DataModel).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
  337. .Where(x => x.Name == nameof(LoadModelTable) && x.IsGenericMethod)
  338. .FirstOrDefault()!;
  339. foreach (var table in _tables)
  340. if (table.Value.ShouldLoad)
  341. if (requiredTables == null || requiredTablesList.Contains(table.Key))
  342. queries[table.Key] = (genericMethod.MakeGenericMethod(table.Value.Type).Invoke(this, new object?[]
  343. {
  344. table.Key,
  345. requiredQueries
  346. }) as IQueryDef)!;
  347. var results = Client.QueryMultiple(queries);
  348. foreach (var result in results)
  349. if (_tables.TryGetValue(result.Key, out var table))
  350. table.Table = result.Value;
  351. else
  352. Logger.Send(LogType.Error, "",
  353. string.Format("QueryMultiple returned table with key {0}, which is not in the data model!", result.Key));
  354. args = new CancelEventArgs();
  355. OnAfterLoad?.Invoke(args);
  356. if (!args.Cancel) AfterLoad(requiredTablesList);
  357. }
  358. public void LoadModel(IEnumerable<string> requiredTables, params IDataModelQueryDef[] requiredQueries)
  359. {
  360. LoadModel(requiredTables, requiredQueries.ToDictionary(x => x.TableName, x => x as IQueryDef));
  361. }
  362. #endregion
  363. #region Non-Generic Stuff
  364. public bool IsChildTable(string tableName)
  365. {
  366. return _relationships.Any(x => x.ChildTable == tableName);
  367. }
  368. public static string TableName(Type type, string? alias = null)
  369. {
  370. return string.IsNullOrWhiteSpace(alias) ? type.EntityName().Split('.').Last() : alias;
  371. }
  372. private void CheckTable(Type type, string? alias = null)
  373. {
  374. var name = TableName(type, alias);
  375. if (!_tables.ContainsKey(name))
  376. throw new Exception(string.Format("No Table for {0}", name));
  377. }
  378. public void AddTable(Type type, CoreTable table, bool isdefault = false, string? alias = null)
  379. {
  380. var name = TableName(type, alias);
  381. if (!_tables.ContainsKey(name))
  382. _tables[name] = new DataModelTable(type, table, isdefault, null, null, false);
  383. else
  384. throw new Exception(string.Format("[{0}] already exists in this data model!", name));
  385. }
  386. public void SetTableData(Type type, CoreTable tableData, string? alias = null)
  387. {
  388. var name = TableName(type, alias);
  389. if (_tables.TryGetValue(name, out var table))
  390. {
  391. table.Table = tableData;
  392. table.ShouldLoad = false;
  393. }
  394. else
  395. {
  396. throw new Exception(string.Format("[{0}] does not exist in this data model!", name));
  397. }
  398. }
  399. public void LinkTable(Type parenttype, string parentcolumn, Type childtype, string childcolumn, string? parentalias = null,
  400. string? childalias = null, bool isLookup = false)
  401. {
  402. CheckTable(parenttype, parentalias);
  403. CheckTable(childtype, childalias);
  404. var relationship = new DataModelRelationship(
  405. TableName(parenttype, parentalias),
  406. parentcolumn,
  407. TableName(childtype, childalias),
  408. childcolumn,
  409. isLookup
  410. );
  411. if (!_relationships.Any(x => x.ParentTable.Equals(relationship.ParentTable) && x.ChildTable.Equals(relationship.ChildTable)))
  412. _relationships.Add(relationship);
  413. }
  414. public bool HasTable(Type type, string? alias = null)
  415. {
  416. var name = TableName(type, alias);
  417. return _tables.ContainsKey(name);
  418. }
  419. #endregion
  420. #region Adding & Linking Tables
  421. public void AddTable<TType>(Filter<TType>? filter, Columns<TType>? columns, bool isdefault = false, string? alias = null, bool shouldLoad = true)
  422. {
  423. var name = TableName<TType>(alias);
  424. if (!_tables.ContainsKey(name))
  425. {
  426. var table = new CoreTable();
  427. if(columns != null)
  428. {
  429. table.LoadColumns(columns);
  430. }
  431. else
  432. {
  433. table.LoadColumns(typeof(TType));
  434. }
  435. _tables[name] = new DataModelTable(typeof(TType), table, isdefault, filter, columns, shouldLoad);
  436. }
  437. }
  438. public void AddChildTable<TParent, TChild>(Expression<Func<TParent, object>> parentcolumn, Expression<Func<TChild, object>> childcolumn,
  439. Filter<TChild>? filter = null, Columns<TChild>? columns = null, bool isdefault = false, string? parentalias = null, string? childalias = null)
  440. {
  441. CheckTable<TParent>(parentalias);
  442. AddTable(filter, columns, isdefault, childalias);
  443. LinkTable(parentcolumn, childcolumn, parentalias, childalias, false);
  444. }
  445. public void AddLookupTable<TSource, TLookup>(Expression<Func<TSource, object>> sourcecolumn, Expression<Func<TLookup, object>> lookupcolumn,
  446. Filter<TLookup>? filter = null, Columns<TLookup>? columns = null, bool isdefault = false,
  447. string? sourcealias = null, string? lookupalias = null)
  448. {
  449. CheckTable<TSource>(sourcealias);
  450. AddTable(filter, columns, isdefault, lookupalias);
  451. LinkTable(sourcecolumn, lookupcolumn, sourcealias, lookupalias, true);
  452. }
  453. public CoreTable GetTable<TType>(string? alias = null)
  454. {
  455. CheckTable<TType>(alias);
  456. var name = TableName<TType>(alias);
  457. return _tables[name].Table;
  458. }
  459. private DataModelTable GetDataModelTable<TType>(string? alias = null)
  460. {
  461. CheckTable<TType>(alias);
  462. var name = TableName<TType>(alias);
  463. return _tables[name];
  464. }
  465. protected bool IsRequired<TType>(IEnumerable<string> requiredtables, string? alias = null)
  466. {
  467. var name = TableName<TType>(alias);
  468. return requiredtables == null || requiredtables.Contains(name);
  469. }
  470. protected bool IsRequired(Type type, IEnumerable<string> requiredtables, string? alias = null)
  471. {
  472. var name = TableName(type, alias);
  473. return requiredtables == null || requiredtables.Contains(name);
  474. }
  475. public void LinkTable<TParent, TChild>(Expression<Func<TParent, object>> parent, Expression<Func<TChild, object>> child,
  476. string? parentalias = null, string? childalias = null, bool isLookup = false)
  477. {
  478. CheckTable<TParent>(parentalias);
  479. CheckTable<TChild>(childalias);
  480. var relationship = new DataModelRelationship<TParent, TChild>(parentalias, parent, childalias, child, isLookup);
  481. if (!_relationships.Any(x => x.ParentTable.Equals(relationship.ParentTable) && x.ChildTable.Equals(relationship.ChildTable)))
  482. _relationships.Add(relationship);
  483. //SetupIDs<TParent>(relationship.ParentColumn);
  484. }
  485. #endregion
  486. #region Getting/Setting Table Data
  487. public Filter<TType>? GetFilter<TType>(string? alias = null)
  488. {
  489. var table = GetDataModelTable<TType>(alias);
  490. return table.Filter as Filter<TType>;
  491. }
  492. public Columns<TType>? GetColumns<TType>(string? alias = null)
  493. {
  494. var table = GetDataModelTable<TType>(alias);
  495. return table.Columns as Columns<TType>;
  496. }
  497. [Obsolete("Use SetColumns instead")]
  498. public void SetTableColumns<TType>(Columns<TType> columns, string? alias = null) => SetColumns(columns, alias);
  499. public void SetFilter<TType>(Filter<TType>? filter, string? alias = null)
  500. {
  501. var table = GetDataModelTable<TType>(alias);
  502. table.Filter = filter;
  503. }
  504. public void SetColumns<TType>(Columns<TType>? columns, string? alias = null)
  505. {
  506. var table = GetDataModelTable<TType>(alias);
  507. table.Columns = columns;
  508. }
  509. public void SetIsDefault<TType>(bool isDefault, string? alias = null)
  510. {
  511. var table = GetDataModelTable<TType>(alias);
  512. table.IsDefault = isDefault;
  513. }
  514. public void SetShouldLoad<TType>(bool shouldLoad, string? alias = null)
  515. {
  516. var table = GetDataModelTable<TType>(alias);
  517. table.ShouldLoad = shouldLoad;
  518. }
  519. #endregion
  520. #region Removing Tables
  521. private bool RemoveTable(Type type, string? alias = null)
  522. {
  523. var name = TableName(type, alias);
  524. return _tables.Remove(name);
  525. }
  526. public bool RemoveTable<TType>(string? alias = null) => RemoveTable(typeof(TType), alias);
  527. #endregion
  528. #region Cache of Link Values based on relationships
  529. // Type = Parent, String = ParentColumn, List=Values
  530. //private Dictionary<Type, Dictionary<String, List<object>>> _ids = new Dictionary<Type, Dictionary<String, List<object>>>();
  531. // private void SetupIds<TType>(String columnname)
  532. //{
  533. // if (!_ids.ContainsKey(typeof(TParent)))
  534. // _ids[typeof(TParent)] = new Dictionary<string, List<object>>();
  535. // _ids[typeof(TParent)][relationship.ParentColumn] = new List<object>();
  536. //}
  537. //private void ClearIDs<TType>()
  538. //{
  539. // if (_ids.ContainsKey(typeof(TType)))
  540. // {
  541. // var cols = _ids[typeof(TType)];
  542. // foreach (var col in cols.Keys)
  543. // cols[col].Clear();
  544. // }
  545. //}
  546. //private void UpdateIDs<TType>()
  547. //{
  548. // if (_ids.ContainsKey(typeof(TType)))
  549. // {
  550. // var cols = _ids[typeof(TType)];
  551. // foreach (var col in cols.Keys)
  552. // cols[col].AddRange(GetTable<TType>().ExtractValues<object>(col, true));
  553. // }
  554. //}
  555. //protected object[] GetIDs<TType>(String column)
  556. //{
  557. // if (_ids.ContainsKey(typeof(TType)))
  558. // {
  559. // var cols = _ids[typeof(TType)];
  560. // if (cols.ContainsKey(column))
  561. // return cols[column].ToArray();
  562. // }
  563. // return new object[] { };
  564. //}
  565. #endregion
  566. }
  567. public abstract class DataModel<T> : DataModel where T : Entity, IRemotable, IPersistent, new()
  568. {
  569. public DataModel(Filter<T> filter, Columns<T>? columns = null, SortOrder<T>? sort = null)
  570. {
  571. Filter = filter;
  572. Columns = columns;
  573. Sort = sort;
  574. AddTable(filter, columns, true);
  575. AddChildTable<T, AuditTrail>(x => x.ID, x => x.EntityID);
  576. }
  577. public Filter<T>? Filter { get; set; }
  578. public Columns<T>? Columns { get; set; }
  579. public SortOrder<T>? Sort { get; set; }
  580. }
  581. public class DataModelRelationship : IDataModelRelationship
  582. {
  583. public DataModelRelationship(string parenttable, string parentcolumn, string childtable, string childcolumn, bool isLookup = false)
  584. {
  585. ParentTable = parenttable;
  586. ParentColumn = parentcolumn;
  587. ChildTable = childtable;
  588. ChildColumn = childcolumn;
  589. IsLookup = isLookup;
  590. }
  591. public string ChildColumn { get; }
  592. public string ChildTable { get; }
  593. public string ParentColumn { get; }
  594. public string ParentTable { get; }
  595. public bool IsLookup { get; }
  596. public DataRelation AsDataRelation()
  597. {
  598. string parentTable, parentColumn, childTable, childColumn;
  599. // Reverse the relationships if it is a lookup
  600. if (IsLookup)
  601. {
  602. parentTable = ChildTable;
  603. parentColumn = ChildColumn;
  604. childTable = ParentTable;
  605. childColumn = ParentColumn;
  606. }
  607. else
  608. {
  609. parentTable = ParentTable;
  610. parentColumn = ParentColumn;
  611. childTable = ChildTable;
  612. childColumn = ChildColumn;
  613. }
  614. var result = new DataRelation(
  615. string.Format("{0}_{1}_{2}_{3}", parentTable, parentColumn, childTable, childColumn),
  616. parentTable,
  617. childTable,
  618. new[] { parentColumn },
  619. new[] { childColumn },
  620. false
  621. );
  622. result.RelationName = string.Format("{0}_{1}_{2}_{3}", parentTable, parentColumn, childTable, childColumn);
  623. return result;
  624. }
  625. public string ParentColumnAsPropertyName()
  626. {
  627. return ParentColumn;
  628. }
  629. public string ChildColumnAsPropertyName()
  630. {
  631. return ChildColumn;
  632. }
  633. }
  634. public class DataModelRelationship<TParent, TChild> : IDataModelRelationship
  635. {
  636. public DataModelRelationship(string? parentalias, Expression<Func<TParent, object>> parent, string? childalias,
  637. Expression<Func<TChild, object>> child, bool isLookup)
  638. {
  639. ParentTable = string.IsNullOrWhiteSpace(parentalias) ? typeof(TParent).EntityName().Split('.').Last() : parentalias;
  640. Parent = parent;
  641. ChildTable = string.IsNullOrWhiteSpace(childalias) ? typeof(TChild).EntityName().Split('.').Last() : childalias;
  642. Child = child;
  643. IsLookup = isLookup;
  644. }
  645. public Expression<Func<TChild, object>> Child { get; }
  646. public Expression<Func<TParent, object>> Parent { get; }
  647. public string ChildTable { get; }
  648. public string ChildColumn => CoreUtils.GetFullPropertyName(Child, ".").Replace('.', '_');
  649. public string ParentTable { get; }
  650. public string ParentColumn => CoreUtils.GetFullPropertyName(Parent, ".").Replace('.', '_');
  651. public bool IsLookup { get; }
  652. public string ParentColumnAsPropertyName()
  653. {
  654. return CoreUtils.GetFullPropertyName(Parent, ".");
  655. }
  656. public string ChildColumnAsPropertyName()
  657. {
  658. return CoreUtils.GetFullPropertyName(Child, ".");
  659. }
  660. public DataRelation AsDataRelation()
  661. {
  662. string parentTable, parentColumn, childTable, childColumn;
  663. // Reverse the relationships if it is a lookup
  664. if (IsLookup)
  665. {
  666. parentTable = ChildTable;
  667. parentColumn = ChildColumn;
  668. childTable = ParentTable;
  669. childColumn = ParentColumn;
  670. }
  671. else
  672. {
  673. parentTable = ParentTable;
  674. parentColumn = ParentColumn;
  675. childTable = ChildTable;
  676. childColumn = ChildColumn;
  677. }
  678. var result = new DataRelation(
  679. string.Format("{0}_{1}_{2}_{3}", parentTable, parentColumn, childTable, childColumn),
  680. parentTable,
  681. childTable,
  682. new[] { parentColumn },
  683. new[] { childColumn },
  684. false
  685. );
  686. result.RelationName = string.Format("{0}_{1}_{2}_{3}", parentTable, parentColumn, childTable, childColumn);
  687. return result;
  688. }
  689. }
  690. }