AppendixObjectContext.cs 9.1 KB

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