DataModel.cs 35 KB

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