DataModel.cs 34 KB

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