DataModel.cs 35 KB

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