DataModel.cs 37 KB

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