DataModel.cs 35 KB

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