RHDWContext.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. using SQLite.CodeFirst;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel.DataAnnotations.Schema;
  5. using System.Data.Common;
  6. using System.Data.Entity;
  7. using System.Data.Entity.Core.Common;
  8. using System.Data.Entity.Infrastructure;
  9. using System.Data.Entity.Infrastructure.Interception;
  10. using System.Data.Entity.ModelConfiguration.Conventions;
  11. using System.Data.Entity.Validation;
  12. using System.Data.SQLite;
  13. using System.Data.SQLite.EF6;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Reflection;
  17. using System.Text.RegularExpressions;
  18. using System.Threading.Tasks;
  19. using XdCxRhDW.Entity;
  20. namespace XdCxRhDW.Repostory
  21. {
  22. public class RHDWLogContext : DbContext
  23. {
  24. public string DbFile;
  25. public RHDWLogContext() : base("LogDbCon") //配置使用的连接名
  26. {
  27. //|DataDirectory|在mvc等程序中代表了App_Data,在普通程序中代表程序根目录
  28. var dbFile = Database.Connection.ConnectionString.Replace("Data Source=", "").Replace("|DataDirectory|\\", "");
  29. this.DbFile = dbFile;
  30. }
  31. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  32. {
  33. this.Database.Log = msg =>
  34. {
  35. };
  36. modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
  37. modelBuilder.Configurations.AddFromAssembly(typeof(RHDWLogContext).Assembly);//自动加载Entity-Type
  38. var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<RHDWLogContext>(modelBuilder);
  39. Database.SetInitializer(sqliteConnectionInitializer);
  40. base.OnModelCreating(modelBuilder);
  41. }
  42. public DbSet<LogRes> LogRes { set; get; }
  43. }
  44. /// <summary>
  45. /// 基础表上下文(id为int)
  46. /// </summary>
  47. public class RHDWContext : DbContext
  48. {
  49. private class DbTableColumnInfo
  50. {
  51. public string name { get; set; }
  52. public string type { get; set; }
  53. public int notnull { get; set; }
  54. public int pk { get; set; }
  55. }
  56. private class DbTableForeignKeyInfo
  57. {
  58. public string from { get; set; }
  59. }
  60. public string DbFile;
  61. public RHDWContext() : base("DbCon") //配置使用的连接名
  62. {
  63. //|DataDirectory|在mvc等程序中代表了App_Data,在普通程序中代表程序根目录
  64. var dbFile = Database.Connection.ConnectionString.Replace("Data Source=","").Replace("|DataDirectory|\\", "");
  65. this.DbFile = dbFile;
  66. }
  67. public Task<List<T>> SqlQueryAsync<T>(string sql)
  68. {
  69. return this.Database.SqlQuery<T>(sql).ToListAsync();
  70. }
  71. public Task<T> SqlQueryOneAsync<T>(string sql)
  72. {
  73. return this.Database.SqlQuery<T>(sql).FirstOrDefaultAsync();
  74. }
  75. //检查数据库表是否缺失
  76. public string CheckTableExist()
  77. {
  78. var tables = this.Database.SqlQuery<string>("select name from sqlite_master where type='table' and name not like 'sqlite%'").ToList();
  79. var props = this.GetType().GetProperties();
  80. List<string> list = new List<string>();
  81. foreach (var prop in props)
  82. {
  83. bool isDbSet = prop.PropertyType.IsGenericType && typeof(DbSet<>) == prop.PropertyType.GetGenericTypeDefinition();
  84. if (isDbSet)
  85. {
  86. var entityType = prop.PropertyType.GenericTypeArguments[0];
  87. var name = entityType.GetCustomAttribute<TableAttribute>()?.Name;
  88. if (name == null)
  89. {
  90. name = entityType.Name;
  91. }
  92. list.Add(name);
  93. }
  94. }
  95. foreach (var item in list)
  96. {
  97. if (!tables.Contains(item))
  98. {
  99. return item;
  100. }
  101. }
  102. return "";
  103. }
  104. public string CheckTableField()
  105. {
  106. var tables = this.Database.SqlQuery<string>("select name from sqlite_master where type='table' and name not like 'sqlite%'").ToList();
  107. var props = this.GetType().GetProperties();
  108. List<Type> entityTypes = new List<Type>();
  109. foreach (var prop in props)
  110. {
  111. bool isDbSet = prop.PropertyType.IsGenericType && typeof(DbSet<>) == prop.PropertyType.GetGenericTypeDefinition();
  112. if (isDbSet)
  113. {
  114. var entityType = prop.PropertyType.GenericTypeArguments[0];
  115. entityTypes.Add(entityType);
  116. }
  117. }
  118. foreach (var table in tables)
  119. {
  120. var res = this.Database.SqlQuery<DbTableColumnInfo>($"PRAGMA table_info([{table}])").ToList();
  121. var entityType = entityTypes.First(p => p.Name == table);
  122. var entityProps = entityType.GetProperties().Where(p =>
  123. p.CanRead
  124. && p.CanWrite
  125. && !p.GetMethod.IsVirtual
  126. && p.GetCustomAttribute<NotMappedAttribute>() == null);
  127. foreach (var prop in entityProps)
  128. {
  129. var find = res.Find(p => p.name == prop.Name);
  130. if (find == null)
  131. {
  132. string typeStr = "";
  133. var type = prop.PropertyType;
  134. if (prop.PropertyType.IsGenericType)
  135. {
  136. type = prop.PropertyType.GenericTypeArguments[0];
  137. }
  138. if (type == typeof(string))
  139. {
  140. typeStr = "nvarchar";
  141. }
  142. else if (type == typeof(int) || type == typeof(long))
  143. {
  144. typeStr = "int";
  145. }
  146. else if (type == typeof(double) || type == typeof(float))
  147. {
  148. typeStr = "float";
  149. }
  150. else if (type == typeof(DateTime))
  151. {
  152. typeStr = "datetime";
  153. }
  154. return $"Database.db数据库表{table}缺少{prop.Name}字段,类型={typeStr}";
  155. }
  156. else
  157. {
  158. if (prop.PropertyType != typeof(string) && find.pk == 0 && !prop.PropertyType.IsGenericType && find.notnull == 0)
  159. {
  160. var foreignInfo = this.Database.SqlQuery<DbTableForeignKeyInfo>($"PRAGMA foreign_key_list({table})").ToList();
  161. if (!foreignInfo.Any(p => p.from == prop.Name))
  162. {
  163. return $"Database.db数据库表{table}中{prop.Name}字段不允许为空";
  164. }
  165. }
  166. }
  167. }
  168. }
  169. return "";
  170. }
  171. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  172. {
  173. this.Database.Log = msg =>
  174. {
  175. };
  176. modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
  177. modelBuilder.Configurations.AddFromAssembly(typeof(RHDWContext).Assembly);//自动加载Entity-Type
  178. var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<RHDWContext>(modelBuilder);
  179. Database.SetInitializer(sqliteConnectionInitializer);
  180. base.OnModelCreating(modelBuilder);
  181. }
  182. public DbSet<XlInfo> XlInfos { set; get; }
  183. public DbSet<TaskInfo> TaskInfos { set; get; }
  184. public DbSet<TaskSig> TaskSigs { set; get; }
  185. public DbSet<TxInfo> TxInfos { get; set; }
  186. public DbSet<SatInfo> SatInfos { get; set; }
  187. public DbSet<FixedStation> FixedStation { get; set; }
  188. public DbSet<SigInfo> SigInfos { get; set; }
  189. public DbSet<SigDelay> SigDelays { get; set; }
  190. public DbSet<TargetInfo> TargetInfos { get; set; }
  191. public DbSet<SysSetings> SysSetings { get; set; }
  192. }
  193. /// <summary>
  194. /// 分区表上下文(id为long)
  195. /// </summary>
  196. public class RHDWPartContext : DbContext
  197. {
  198. public static RHDWPartContext GetContext(string dbFile, bool createDb = false)
  199. {
  200. if (!File.Exists(dbFile) && !createDb)
  201. {
  202. return null;
  203. }
  204. var connectionString = $@"Data Source={dbFile}";
  205. SQLiteConnection con = new SQLiteConnection(connectionString);
  206. return new RHDWPartContext(con);
  207. }
  208. public static RHDWPartContext GetContext(DateTime partTime, bool createDb = false, string prefix = "")
  209. {
  210. var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DbPart");
  211. var dayFile = Path.Combine(dir, $@"{partTime.Year}\{prefix}{partTime:MMdd}.db");
  212. if (!File.Exists(dayFile) && !createDb)
  213. {
  214. return null;
  215. }
  216. var connectionString = $@"Data Source=|DataDirectory|\DbPart\{partTime.Year}\{prefix}{partTime:MMdd}.db";
  217. SQLiteConnection con = new SQLiteConnection(connectionString);
  218. return new RHDWPartContext(con);
  219. }
  220. private RHDWPartContext(DbConnection con)
  221. : base(con, true)
  222. {
  223. }
  224. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  225. {
  226. this.Database.Log = msg =>
  227. {
  228. };
  229. modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
  230. modelBuilder.Configurations.AddFromAssembly(typeof(RHDWPartContext).Assembly);
  231. var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<RHDWPartContext>(modelBuilder);
  232. Database.SetInitializer(sqliteConnectionInitializer);
  233. base.OnModelCreating(modelBuilder);
  234. }
  235. public DbSet<StationRes> StationRes { get; set; }
  236. public DbSet<CxRes> CxRes { get; set; }
  237. public DbSet<CgRes> CgRes { get; set; }
  238. public DbSet<CgXgfRes> CgXgfRes { get; set; }
  239. public DbSet<PosRes> PosRes { get; set; }
  240. public DbSet<CheckRes> CheckRes { get; set; }
  241. }
  242. public class SqliteConfiguration : DbConfiguration
  243. {
  244. public SqliteConfiguration()
  245. {
  246. DbInterception.Add(new SqliteInterceptor());//拦截器
  247. SetProviderFactory("System.Data.SQLite", SQLiteFactory.Instance);
  248. SetProviderFactory("System.Data.SQLite.EF6", SQLiteProviderFactory.Instance);
  249. SetProviderServices("System.Data.SQLite", (DbProviderServices)SQLiteProviderFactory.Instance.GetService(typeof(DbProviderServices)));
  250. }
  251. }
  252. }