AppendixObjectContext.cs 8.8 KB

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