AppendixObjectContext.cs 8.1 KB

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