AppendixObjectContext.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. using GreenTree.Nachtragsmanagement.Core.Domain.Config;
  24. using GreenTree.Nachtragsmanagement.Data.Mapping.Config;
  25. using GreenTree.Nachtragsmanagement.Core.Domain.Logging;
  26. using GreenTree.Nachtragsmanagement.Data.Mapping.Logging;
  27. namespace GreenTree.Nachtragsmanagement.Data
  28. {
  29. public class AppendixObjectContext : DbContext, IDbContext
  30. {
  31. #region DbSets
  32. private List<object> _dbSets = new List<object>();
  33. #endregion
  34. #region Ctor
  35. /// <summary>
  36. /// Initializes a new instance of the AppendixObjectContext-class
  37. /// </summary>
  38. /// <param name="nameOrConnectionString"></param>
  39. public AppendixObjectContext(string nameOrConnectionString)
  40. : base(nameOrConnectionString)
  41. {
  42. var userSet = Set<User>();
  43. var roleSet = Set<Role>();
  44. var functionSet = Set<Function>();
  45. var siteSet = Set<Site>();
  46. var invoiceSet = Set<Invoice>();
  47. var statusSet = Set<Status>();
  48. var kindSet = Set<Kind>();
  49. var disturbanceSet = Set<Disturbance>();
  50. var deviationSet = Set<Deviation>();
  51. var categorySet = Set<Category>();
  52. var stateSet = Set<State>();
  53. var appendixSet = Set<Appendix>();
  54. var mailNotificationSet = Set<MailNotification>();
  55. var dbContextSpecSet = Set<DbContextSpec>();
  56. var configItemSet = Set<ConfigItem>();
  57. var loggingSet = Set<Log>();
  58. _dbSets.AddRange(
  59. new object[]
  60. {
  61. userSet,
  62. roleSet,
  63. functionSet,
  64. siteSet,
  65. invoiceSet,
  66. statusSet,
  67. kindSet,
  68. disturbanceSet,
  69. deviationSet,
  70. categorySet,
  71. stateSet,
  72. appendixSet,
  73. mailNotificationSet,
  74. dbContextSpecSet,
  75. configItemSet,
  76. loggingSet
  77. }
  78. );
  79. //Database.SetInitializer(new CreateDatabaseIfNotExists<AppendixObjectContext>());
  80. Database.SetInitializer(new DropCreateDatabaseIfModelChanges<AppendixObjectContext>());
  81. Database.CreateIfNotExists();
  82. ((IObjectContextAdapter)this).ObjectContext.ContextOptions.LazyLoadingEnabled = true;
  83. SaveChanges();
  84. }
  85. #endregion
  86. #region Utilities
  87. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  88. {
  89. modelBuilder.Configurations.Add(new UserMap());
  90. modelBuilder.Configurations.Add(new RoleMap());
  91. modelBuilder.Configurations.Add(new FunctionMap());
  92. modelBuilder.Configurations.Add(new SiteMap());
  93. modelBuilder.Configurations.Add(new InvoiceMap());
  94. modelBuilder.Configurations.Add(new StatusMap());
  95. modelBuilder.Configurations.Add(new KindMap());
  96. modelBuilder.Configurations.Add(new DisturbanceMap());
  97. modelBuilder.Configurations.Add(new DisturbanceValueMap());
  98. modelBuilder.Configurations.Add(new DeviationMap());
  99. modelBuilder.Configurations.Add(new CategoryMap());
  100. modelBuilder.Configurations.Add(new CategoryValueMap());
  101. modelBuilder.Configurations.Add(new AppendixMap());
  102. modelBuilder.Configurations.Add(new MailNotificationMap());
  103. modelBuilder.Configurations.Add(new DbContextSpecMap());
  104. modelBuilder.Configurations.Add(new ConfigItemMap());
  105. modelBuilder.Configurations.Add(new LogMap());
  106. base.OnModelCreating(modelBuilder);
  107. }
  108. /// <summary>
  109. /// Attach an entity to the context or return an already attached entity (if it was already attached)
  110. /// </summary>
  111. /// <typeparam name="TEntity">TEntity</typeparam>
  112. /// <param name="entity">Entity</param>
  113. /// <returns>Attached entity</returns>
  114. protected virtual TEntity AttachEntityToContext<TEntity>(TEntity entity) where TEntity : BaseEntity, new()
  115. {
  116. //little hack here until Entity Framework really supports stored procedures
  117. //otherwise, navigation properties of loaded entities are not loaded until an entity is attached to the context
  118. var alreadyAttached = Set<TEntity>().Local.FirstOrDefault(x => x.Id == entity.Id);
  119. if (alreadyAttached == null)
  120. {
  121. //attach new entity
  122. Set<TEntity>().Attach(entity);
  123. return entity;
  124. }
  125. //entity is already loaded
  126. return alreadyAttached;
  127. }
  128. #endregion
  129. #region Methods
  130. /// <summary>
  131. /// Create database script
  132. /// </summary>
  133. /// <returns>SQL to generate database</returns>
  134. public string CreateDatabaseScript()
  135. {
  136. return ((IObjectContextAdapter)this).ObjectContext.CreateDatabaseScript();
  137. }
  138. /// <summary>
  139. /// Get the DbSet of a specific entity which inherits the BaseEntity class
  140. /// </summary>
  141. /// <typeparam name="TEntity"></typeparam>
  142. /// <returns></returns>
  143. public IDbSet<TEntity> Get<TEntity>() where TEntity : BaseEntity
  144. {
  145. var entityType = typeof(TEntity);
  146. var dbSet = _dbSets
  147. .FirstOrDefault(d => d.GetType().GetGenericArguments()[0].FullName == entityType.FullName);
  148. return (IDbSet<TEntity>)dbSet;
  149. }
  150. /// <summary>
  151. /// Set DbSet
  152. /// </summary>
  153. /// <typeparam name="TEntity">Entity type</typeparam>
  154. /// <returns>DbSet</returns>
  155. public new IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
  156. {
  157. return base.Set<TEntity>();
  158. }
  159. /// <summary>
  160. /// 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.
  161. /// </summary>
  162. /// <typeparam name="TElement">The type of object returned by the query.</typeparam>
  163. /// <param name="sql">The SQL query string.</param>
  164. /// <param name="parameters">The parameters to apply to the SQL query string.</param>
  165. /// <returns>Result</returns>
  166. public IEnumerable<TElement> SqlQuery<TElement>(string sql, params object[] parameters)
  167. {
  168. return Database.SqlQuery<TElement>(sql, parameters);
  169. }
  170. /// <summary>
  171. /// Executes the given DDL/DML command against the database.
  172. /// </summary>
  173. /// <param name="sql">The command string</param>
  174. /// <param name="doNotEnsureTransaction">false - the transaction creation is not ensured; true - the transaction creation is ensured.</param>
  175. /// <param name="timeout">Timeout value, in seconds. A null value indicates that the default value of the underlying provider will be used</param>
  176. /// <param name="parameters">The parameters to apply to the command string.</param>
  177. /// <returns>The result returned by the database after executing the command.</returns>
  178. public int ExecuteSqlCommand(string sql, bool doNotEnsureTransaction = false, int? timeout = null, params object[] parameters)
  179. {
  180. int? previousTimeout = null;
  181. if (timeout.HasValue)
  182. {
  183. //store previous timeout
  184. previousTimeout = ((IObjectContextAdapter)this).ObjectContext.CommandTimeout;
  185. ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = timeout;
  186. }
  187. var transactionalBehavior = doNotEnsureTransaction
  188. ? TransactionalBehavior.DoNotEnsureTransaction
  189. : TransactionalBehavior.EnsureTransaction;
  190. var result = this.Database.ExecuteSqlCommand(transactionalBehavior, sql, parameters);
  191. if (timeout.HasValue)
  192. {
  193. //Set previous timeout back
  194. ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = previousTimeout;
  195. }
  196. //return result
  197. return result;
  198. }
  199. #endregion
  200. }
  201. }