AppendixObjectContext.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.Common;
  4. using System.Data.Entity;
  5. using System.Data.Entity.Infrastructure;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using GreenTree.Nachtragsmanagement.Core;
  11. using GreenTree.Nachtragsmanagement.Core.Domain.Appendix;
  12. using GreenTree.Nachtragsmanagement.Core.Domain.Deviation;
  13. using GreenTree.Nachtragsmanagement.Core.Domain.Invoice;
  14. using GreenTree.Nachtragsmanagement.Core.Domain.Misc;
  15. using GreenTree.Nachtragsmanagement.Core.Domain.Site;
  16. using GreenTree.Nachtragsmanagement.Core.Domain.User;
  17. using GreenTree.Nachtragsmanagement.Data.Mapping.Appendix;
  18. using GreenTree.Nachtragsmanagement.Data.Mapping.Deviation;
  19. using GreenTree.Nachtragsmanagement.Data.Mapping.Misc;
  20. using GreenTree.Nachtragsmanagement.Data.Mapping.Site;
  21. using GreenTree.Nachtragsmanagement.Data.Mapping.User;
  22. using System.Data.Entity.Migrations;
  23. namespace GreenTree.Nachtragsmanagement.Data
  24. {
  25. public class AppendixObjectContext : DbContext, IDbContext
  26. {
  27. #region DbSets
  28. private List<object> _dbSets = new List<object>();
  29. #endregion
  30. #region Ctor
  31. /// <summary>
  32. /// Initializes a new instance of the AppendixObjectContext-class
  33. /// </summary>
  34. /// <param name="nameOrConnectionString"></param>
  35. public AppendixObjectContext(string nameOrConnectionString)
  36. : base(nameOrConnectionString)
  37. {
  38. //((IObjectContextAdapter) this).ObjectContext.ContextOptions.LazyLoadingEnabled = true;
  39. var userSet = Set<User>();
  40. var roleSet = Set<Role>();
  41. var functionSet = Set<Function>();
  42. var siteSet = Set<Site>();
  43. var invoiceSet = Set<Invoice>();
  44. var statusSet = Set<Status>();
  45. var kindSet = Set<Kind>();
  46. var disturbanceSet = Set<Disturbance>();
  47. var deviationSet = Set<Deviation>();
  48. var categorySet = Set<Category>();
  49. var appendixSet = Set<Appendix>();
  50. var mailNotificationSet = Set<MailNotification>();
  51. var notificationEventSet = Set<NotificationEvent>();
  52. var notificationEventTypeSet = Set<NotificationEventType>();
  53. var dbContextSpecSet = Set<DbContextSpec>();
  54. _dbSets.AddRange(
  55. new object[]
  56. {
  57. userSet,
  58. roleSet,
  59. functionSet,
  60. siteSet,
  61. invoiceSet,
  62. statusSet,
  63. kindSet,
  64. disturbanceSet,
  65. deviationSet,
  66. categorySet,
  67. appendixSet,
  68. mailNotificationSet,
  69. notificationEventSet,
  70. notificationEventTypeSet,
  71. dbContextSpecSet
  72. }
  73. );
  74. Database.SetInitializer(new CreateDatabaseIfNotExists<AppendixObjectContext>());
  75. //Database.SetInitializer(new DropCreateDatabaseIfModelChanges<AppendixObjectContext>());
  76. Database.CreateIfNotExists();
  77. GenerateTestData();
  78. SaveChanges();
  79. }
  80. #endregion
  81. #region Utilities
  82. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  83. {
  84. modelBuilder.Configurations.Add(new UserMap());
  85. modelBuilder.Configurations.Add(new RoleMap());
  86. modelBuilder.Configurations.Add(new FunctionMap());
  87. modelBuilder.Configurations.Add(new SiteMap());
  88. modelBuilder.Configurations.Add(new InvoiceMap());
  89. modelBuilder.Configurations.Add(new StatusMap());
  90. modelBuilder.Configurations.Add(new KindMap());
  91. modelBuilder.Configurations.Add(new DisturbanceMap());
  92. modelBuilder.Configurations.Add(new DeviationMap());
  93. modelBuilder.Configurations.Add(new CategoryMap());
  94. modelBuilder.Configurations.Add(new AppendixMap());
  95. modelBuilder.Configurations.Add(new MailNotificationMap());
  96. modelBuilder.Configurations.Add(new NotificationEventMap());
  97. modelBuilder.Configurations.Add(new NotificationEventTypeMap());
  98. modelBuilder.Configurations.Add(new DbContextSpecMap());
  99. base.OnModelCreating(modelBuilder);
  100. }
  101. /// <summary>
  102. /// Attach an entity to the context or return an already attached entity (if it was already attached)
  103. /// </summary>
  104. /// <typeparam name="TEntity">TEntity</typeparam>
  105. /// <param name="entity">Entity</param>
  106. /// <returns>Attached entity</returns>
  107. protected virtual TEntity AttachEntityToContext<TEntity>(TEntity entity) where TEntity : BaseEntity, new()
  108. {
  109. //little hack here until Entity Framework really supports stored procedures
  110. //otherwise, navigation properties of loaded entities are not loaded until an entity is attached to the context
  111. var alreadyAttached = Set<TEntity>().Local.FirstOrDefault(x => x.Id == entity.Id);
  112. if (alreadyAttached == null)
  113. {
  114. //attach new entity
  115. Set<TEntity>().Attach(entity);
  116. return entity;
  117. }
  118. //entity is already loaded
  119. return alreadyAttached;
  120. }
  121. #endregion
  122. #region Methods
  123. /// <summary>
  124. /// Create database script
  125. /// </summary>
  126. /// <returns>SQL to generate database</returns>
  127. public string CreateDatabaseScript()
  128. {
  129. return ((IObjectContextAdapter)this).ObjectContext.CreateDatabaseScript();
  130. }
  131. /// <summary>
  132. /// Get the DbSet of a specific entity which inherits the BaseEntity class
  133. /// </summary>
  134. /// <typeparam name="TEntity"></typeparam>
  135. /// <returns></returns>
  136. public IDbSet<TEntity> Get<TEntity>() where TEntity : BaseEntity
  137. {
  138. var entityType = typeof(TEntity);
  139. var dbSet = _dbSets
  140. .FirstOrDefault(d => d.GetType().GetGenericArguments()[0].FullName == entityType.FullName);
  141. return (IDbSet<TEntity>)dbSet;
  142. }
  143. /// <summary>
  144. /// Set DbSet
  145. /// </summary>
  146. /// <typeparam name="TEntity">Entity type</typeparam>
  147. /// <returns>DbSet</returns>
  148. public new IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
  149. {
  150. return base.Set<TEntity>();
  151. }
  152. /// <summary>
  153. /// Creates a raw SQL query that will return elements of the given generic type. The type can be any type that has properties that match the names of the columns returned from the query, or can be a simple primitive type. The type does not have to be an entity type. The results of this query are never tracked by the context even if the type of object returned is an entity type.
  154. /// </summary>
  155. /// <typeparam name="TElement">The type of object returned by the query.</typeparam>
  156. /// <param name="sql">The SQL query string.</param>
  157. /// <param name="parameters">The parameters to apply to the SQL query string.</param>
  158. /// <returns>Result</returns>
  159. public IEnumerable<TElement> SqlQuery<TElement>(string sql, params object[] parameters)
  160. {
  161. return Database.SqlQuery<TElement>(sql, parameters);
  162. }
  163. /// <summary>
  164. /// Executes the given DDL/DML command against the database.
  165. /// </summary>
  166. /// <param name="sql">The command string</param>
  167. /// <param name="doNotEnsureTransaction">false - the transaction creation is not ensured; true - the transaction creation is ensured.</param>
  168. /// <param name="timeout">Timeout value, in seconds. A null value indicates that the default value of the underlying provider will be used</param>
  169. /// <param name="parameters">The parameters to apply to the command string.</param>
  170. /// <returns>The result returned by the database after executing the command.</returns>
  171. public int ExecuteSqlCommand(string sql, bool doNotEnsureTransaction = false, int? timeout = null, params object[] parameters)
  172. {
  173. int? previousTimeout = null;
  174. if (timeout.HasValue)
  175. {
  176. //store previous timeout
  177. previousTimeout = ((IObjectContextAdapter)this).ObjectContext.CommandTimeout;
  178. ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = timeout;
  179. }
  180. var transactionalBehavior = doNotEnsureTransaction
  181. ? TransactionalBehavior.DoNotEnsureTransaction
  182. : TransactionalBehavior.EnsureTransaction;
  183. var result = this.Database.ExecuteSqlCommand(transactionalBehavior, sql, parameters);
  184. if (timeout.HasValue)
  185. {
  186. //Set previous timeout back
  187. ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = previousTimeout;
  188. }
  189. //return result
  190. return result;
  191. }
  192. #endregion
  193. #region Test
  194. /// <summary>
  195. /// Generates local test data
  196. /// </summary>
  197. public void GenerateTestData()
  198. {
  199. var isTestDataGeneratedEntity = Get<DbContextSpec>().FirstOrDefault(d => d.Name == "IsTestDataGenerated");
  200. if (isTestDataGeneratedEntity != null && Convert.ToBoolean(isTestDataGeneratedEntity.Value))
  201. return;
  202. var r1 = Get<Role>().Add(new Role
  203. {
  204. Description = "Administrator",
  205. Level = 100
  206. });
  207. var r2 = Get<Role>().Add(new Role
  208. {
  209. Description = "Kaufmann",
  210. Level = 10
  211. });
  212. var r3 = Get<Role>().Add(new Role
  213. {
  214. Description = "Nachtragsmanager",
  215. Level = 10
  216. });
  217. SaveChanges();
  218. var u1 = Get<User>().Add(new User
  219. {
  220. Forename = "Arne",
  221. Lastname = "Diekmann",
  222. CustomNumber = "anw0486m",
  223. MailAddress = "a.diekmann@porta.de",
  224. Password = StaticHelper.GetMD5Hash("14595809")
  225. });
  226. SaveChanges();
  227. u1.Roles.Add(r1);
  228. u1.Roles.Add(r2);
  229. u1.Roles.Add(r3);
  230. SaveChanges();
  231. var db1 = Get<DbContextSpec>().Add(new DbContextSpec
  232. {
  233. Name = "IsTestDataGenerated",
  234. Value = "True"
  235. });
  236. SaveChanges();
  237. }
  238. #endregion
  239. }
  240. }