AppendixObjectContext.cs 7.9 KB

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