RHDWContext.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. using SQLite.CodeFirst;
  2. using System;
  3. using System.Data.Common;
  4. using System.Data.Entity;
  5. using System.Data.Entity.Core.Common;
  6. using System.Data.Entity.Infrastructure.Interception;
  7. using System.Data.Entity.ModelConfiguration.Conventions;
  8. using System.Data.SQLite;
  9. using System.Data.SQLite.EF6;
  10. using System.IO;
  11. using System.Text.RegularExpressions;
  12. using XdCxRhDW.Entity;
  13. namespace XdCxRhDW.Repostory
  14. {
  15. /// <summary>
  16. /// 基础表上下文(id为int)
  17. /// </summary>
  18. [DbConfigurationType(typeof(SqliteConfiguration))]
  19. public class RHDWContext : DbContext
  20. {
  21. public RHDWContext() : base("DbCon") //配置使用的连接名
  22. {
  23. }
  24. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  25. {
  26. this.Database.Log = msg =>
  27. {
  28. };
  29. modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
  30. //modelBuilder.Configurations.Add<RHDWContext>(new EntityTypeConfiguration<RHDWContext>());//new SqliteConfiguration()
  31. modelBuilder.Configurations.AddFromAssembly(typeof(RHDWContext).Assembly);//自动加载SqliteConfiguration
  32. var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<RHDWContext>(modelBuilder);
  33. Database.SetInitializer(sqliteConnectionInitializer);
  34. DbInterception.Add(new SqliteInterceptor());//拦截器
  35. base.OnModelCreating(modelBuilder);
  36. }
  37. public DbSet<XlInfo> XlInfos { set; get; }
  38. public DbSet<TaskInfo> TaskInfos { set; get; }
  39. public DbSet<TxInfo> TxInfos { get; set; }
  40. public DbSet<SatInfo> SatInfos { get; set; }
  41. public DbSet<SigInfo> SigInfos { get; set; }
  42. public DbSet<SigDelay> SigDelays { get; set; }
  43. public DbSet<TargetInfo> TargetInfos { get; set; }
  44. public DbSet<SysSetings> SysSetings { get; set; }
  45. }
  46. /// <summary>
  47. /// 分区表上下文(id为long)
  48. /// </summary>
  49. [DbConfigurationType(typeof(SqliteConfiguration))]
  50. public class RHDWPartContext : DbContext
  51. {
  52. public bool DatabaseExist = false;
  53. public static RHDWPartContext GetContext(string dbFile)
  54. {
  55. var connectionString = $@"Data Source={dbFile}";
  56. SQLiteConnection con = new SQLiteConnection(connectionString);
  57. bool databaseExist = File.Exists(dbFile);
  58. return new RHDWPartContext(con) { DatabaseExist = databaseExist };
  59. }
  60. public static RHDWPartContext GetContext(DateTime partTime, bool isCreateDb = false, string prefix = "")
  61. {
  62. var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DbPart");
  63. var dayFile = Path.Combine(dir, $@"{partTime.Year}\{prefix}{partTime:MMdd}.db");
  64. bool databaseExist = File.Exists(dayFile);
  65. if (isCreateDb)
  66. {
  67. databaseExist = true;
  68. }
  69. var connectionString = $@"Data Source=|DataDirectory|\DbPart\{partTime.Year}\{prefix}{partTime:MMdd}.db";
  70. SQLiteConnection con = new SQLiteConnection(connectionString);
  71. return new RHDWPartContext(con) { DatabaseExist = databaseExist };
  72. }
  73. private RHDWPartContext(DbConnection con)
  74. : base(con, true)
  75. {
  76. }
  77. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  78. {
  79. this.Database.Log = msg =>
  80. {
  81. };
  82. modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
  83. modelBuilder.Configurations.AddFromAssembly(typeof(RHDWPartContext).Assembly);
  84. var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<RHDWPartContext>(modelBuilder);
  85. Database.SetInitializer(sqliteConnectionInitializer);
  86. DbInterception.Add(new SqliteInterceptor());//拦截器
  87. base.OnModelCreating(modelBuilder);
  88. }
  89. public DbSet<StationRes> StationRes { get; set; }
  90. public DbSet<CxRes> CxRes { get; set; }
  91. public DbSet<CgRes> CgRes { get; set; }
  92. public DbSet<CgXgfRes> CgXgfRes { get; set; }
  93. public DbSet<PosRes> PosRes { get; set; }
  94. public DbSet<CheckRes> CheckRes { get; set; }
  95. }
  96. /// <summary>
  97. /// 分区表上下文(id为long)
  98. /// </summary>
  99. [DbConfigurationType(typeof(PartSqliteInterceptor))]
  100. public class RHDWPartReadContext : DbContext
  101. {
  102. public bool DatabaseExist = false;
  103. private string dbFile;
  104. public static RHDWPartReadContext GetContext(string dbFile)
  105. {
  106. var connectionString = $@"Data Source={dbFile}";
  107. SQLiteConnection con = new SQLiteConnection(connectionString);
  108. bool databaseExist = File.Exists(dbFile);
  109. return new RHDWPartReadContext(con) { DatabaseExist = databaseExist, dbFile = dbFile };
  110. }
  111. public static RHDWPartReadContext GetContext(DateTime partTime, bool isCreateDb = false, string prefix = "")
  112. {
  113. var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DbPart");
  114. var dayFile = Path.Combine(dir, $@"{partTime.Year}\{prefix}{partTime:MMdd}.db");
  115. bool databaseExist = File.Exists(dayFile);
  116. if (isCreateDb)
  117. {
  118. databaseExist = true;
  119. }
  120. var connectionString = $@"Data Source=|DataDirectory|\DbPart\{partTime.Year}\{prefix}{partTime:MMdd}.db";
  121. SQLiteConnection con = new SQLiteConnection(connectionString);
  122. return new RHDWPartReadContext(con) { DatabaseExist = databaseExist, dbFile= dayFile };
  123. }
  124. private RHDWPartReadContext(DbConnection con)
  125. : base(con, true)
  126. {
  127. }
  128. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  129. {
  130. this.Database.Log = msg =>
  131. {
  132. };
  133. modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
  134. modelBuilder.Configurations.AddFromAssembly(typeof(RHDWPartReadContext).Assembly);
  135. Database.SetInitializer<RHDWPartReadContext>(null);
  136. // DbInterception.Add(new PartSqliteInterceptor(this.dbFile));//拦截器
  137. base.OnModelCreating(modelBuilder);
  138. }
  139. public DbSet<StationRes> StationRes { get; set; }
  140. public DbSet<CxRes> CxRes { get; set; }
  141. public DbSet<CgRes> CgRes { get; set; }
  142. public DbSet<CgXgfRes> CgXgfRes { get; set; }
  143. public DbSet<PosRes> PosRes { get; set; }
  144. public DbSet<CheckRes> CheckRes { get; set; }
  145. }
  146. /// <summary>
  147. /// Sqlite拦截器.
  148. /// contains或indexOf成的CHARINDEX函数在sqlite里面并不支持,需要拦截转换成LIKE语句
  149. /// </summary>
  150. public class PartSqliteInterceptor : IDbCommandInterceptor
  151. {
  152. private readonly string dbFile;
  153. public PartSqliteInterceptor(string dbFile)
  154. {
  155. this.dbFile = dbFile;
  156. }
  157. private static Regex replaceRegex = new Regex(@"\(CHARINDEX\((.*?),\s?(.*?)\)\)\s*?>\s*?0");
  158. public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
  159. {
  160. }
  161. public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
  162. {
  163. }
  164. public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
  165. {
  166. }
  167. public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
  168. {
  169. if (!File.Exists(dbFile))
  170. interceptionContext.Result = null;
  171. else
  172. ReplaceCharIndexFunc(command);
  173. }
  174. public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
  175. {
  176. }
  177. public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
  178. {
  179. if (!File.Exists(dbFile))
  180. interceptionContext.Result = null;
  181. else
  182. ReplaceCharIndexFunc(command);
  183. }
  184. private void ReplaceCharIndexFunc(DbCommand command)
  185. {
  186. bool isMatch = false;
  187. var text = replaceRegex.Replace(command.CommandText, (match) =>
  188. {
  189. if (match.Success)
  190. {
  191. string paramsKey = match.Groups[1].Value;
  192. string paramsColumnName = match.Groups[2].Value;
  193. //replaceParams
  194. foreach (DbParameter param in command.Parameters)
  195. {
  196. if (param.ParameterName == paramsKey.Substring(1))
  197. {
  198. param.Value = string.Format("%{0}%", param.Value);
  199. break;
  200. }
  201. }
  202. isMatch = true;
  203. return string.Format("{0} LIKE {1}", paramsColumnName, paramsKey);
  204. }
  205. else
  206. return match.Value;
  207. });
  208. if (isMatch)
  209. command.CommandText = text;
  210. }
  211. }
  212. public class SqliteConfiguration : DbConfiguration
  213. {
  214. public SqliteConfiguration()
  215. {
  216. SetProviderFactory("System.Data.SQLite", SQLiteFactory.Instance);
  217. SetProviderFactory("System.Data.SQLite.EF6", SQLiteProviderFactory.Instance);
  218. SetProviderServices("System.Data.SQLite", (DbProviderServices)SQLiteProviderFactory.Instance.GetService(typeof(DbProviderServices)));
  219. }
  220. }
  221. public class DbPartSqliteConfiguration : DbConfiguration
  222. {
  223. public DbPartSqliteConfiguration(IDbInterceptor dbInterceptor)
  224. {
  225. base.AddInterceptor(dbInterceptor);
  226. }
  227. }
  228. }