AppendixObjectContext.cs 8.8 KB

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