RHDWContext.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. class DbTableColumnInfo
  23. {
  24. public string name { get; set; }
  25. public string type { get; set; }
  26. public int notnull { get; set; }
  27. public int pk { get; set; }
  28. }
  29. class DbTableForeignKeyInfo
  30. {
  31. public string from { get; set; }
  32. }
  33. public class RHDWLogContext : DbContext
  34. {
  35. public string DbFile;
  36. public RHDWLogContext() : base("LogDbCon") //配置使用的连接名
  37. {
  38. //|DataDirectory|在mvc等程序中代表了App_Data,在普通程序中代表程序根目录
  39. var dbFile = Database.Connection.ConnectionString.Replace("Data Source=", "").Replace("|DataDirectory|\\", "");
  40. this.DbFile = dbFile;
  41. }
  42. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  43. {
  44. this.Database.Log = msg =>
  45. {
  46. };
  47. modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
  48. modelBuilder.Configurations.AddFromAssembly(typeof(RHDWLogContext).Assembly);//自动加载Entity-Type
  49. var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<RHDWLogContext>(modelBuilder);
  50. Database.SetInitializer(sqliteConnectionInitializer);
  51. base.OnModelCreating(modelBuilder);
  52. }
  53. public DbSet<LogRes> LogRes { set; get; }
  54. }
  55. /// <summary>
  56. /// 基础表上下文(id为int)
  57. /// </summary>
  58. public class RHDWContext : DbContext
  59. {
  60. public string DbFile;
  61. public RHDWContext() : base("DbCon") //配置使用的连接名
  62. {
  63. //|DataDirectory|在mvc等程序中代表了App_Data,在普通程序中代表程序根目录
  64. this.DbFile = Database.Connection.ConnectionString.Replace("Data Source=", "").Replace("|DataDirectory|\\", "");
  65. }
  66. public Task<List<T>> SqlQueryAsync<T>(string sql)
  67. {
  68. return this.Database.SqlQuery<T>(sql).ToListAsync();
  69. }
  70. public Task<T> SqlQueryOneAsync<T>(string sql)
  71. {
  72. return this.Database.SqlQuery<T>(sql).FirstOrDefaultAsync();
  73. }
  74. //检查数据库表是否缺失
  75. public string CheckTableExist()
  76. {
  77. var tables = this.Database.SqlQuery<string>("select name from sqlite_master where type='table' and name not like 'sqlite%'").ToList();
  78. var props = this.GetType().GetProperties();
  79. List<string> list = new List<string>();
  80. foreach (var prop in props)
  81. {
  82. bool isDbSet = prop.PropertyType.IsGenericType && typeof(DbSet<>) == prop.PropertyType.GetGenericTypeDefinition();
  83. if (isDbSet)
  84. {
  85. var entityType = prop.PropertyType.GenericTypeArguments[0];
  86. var name = entityType.GetCustomAttribute<TableAttribute>()?.Name;
  87. if (name == null)
  88. {
  89. name = entityType.Name;
  90. }
  91. list.Add(name);
  92. }
  93. }
  94. foreach (var item in list)
  95. {
  96. if (!tables.Contains(item))
  97. {
  98. return item;
  99. }
  100. }
  101. return "";
  102. }
  103. public string CheckTableField()
  104. {
  105. var tables = this.Database.SqlQuery<string>("select name from sqlite_master where type='table' and name not like 'sqlite%'").ToList();
  106. var props = this.GetType().GetProperties();
  107. List<Type> entityTypes = new List<Type>();
  108. foreach (var prop in props)
  109. {
  110. bool isDbSet = prop.PropertyType.IsGenericType && typeof(DbSet<>) == prop.PropertyType.GetGenericTypeDefinition();
  111. if (isDbSet)
  112. {
  113. var entityType = prop.PropertyType.GenericTypeArguments[0];
  114. entityTypes.Add(entityType);
  115. }
  116. }
  117. foreach (var table in tables)
  118. {
  119. var res = this.Database.SqlQuery<DbTableColumnInfo>($"PRAGMA table_info([{table}])").ToList();
  120. var entityType = entityTypes.First(p => p.Name == table);
  121. var entityProps = entityType.GetProperties().Where(p =>
  122. p.CanRead
  123. && p.CanWrite
  124. && !p.GetMethod.IsVirtual
  125. && p.GetCustomAttribute<NotMappedAttribute>() == null);
  126. foreach (var prop in entityProps)
  127. {
  128. var find = res.Find(p => p.name == prop.Name);
  129. if (find == null)
  130. {
  131. string typeStr = "";
  132. var type = prop.PropertyType;
  133. if (prop.PropertyType.IsGenericType)
  134. {
  135. type = prop.PropertyType.GenericTypeArguments[0];
  136. }
  137. if (type == typeof(string))
  138. {
  139. typeStr = "nvarchar";
  140. }
  141. else if (type == typeof(int) || type == typeof(long))
  142. {
  143. typeStr = "int";
  144. }
  145. else if (type == typeof(double) || type == typeof(float))
  146. {
  147. typeStr = "float";
  148. }
  149. else if (type == typeof(DateTime))
  150. {
  151. typeStr = "datetime";
  152. }
  153. return $"{DbFile}数据库表{table}缺少{prop.Name}字段,类型={typeStr}";
  154. }
  155. else
  156. {
  157. if (prop.PropertyType != typeof(string) && find.pk == 0 && !prop.PropertyType.IsGenericType && find.notnull == 0)
  158. {
  159. var foreignInfo = this.Database.SqlQuery<DbTableForeignKeyInfo>($"PRAGMA foreign_key_list({table})").ToList();
  160. if (!foreignInfo.Any(p => p.from == prop.Name))
  161. {
  162. return $"{DbFile}数据库表{table}中{prop.Name}字段不允许为空";
  163. }
  164. }
  165. }
  166. }
  167. }
  168. return "";
  169. }
  170. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  171. {
  172. this.Database.Log = msg =>
  173. {
  174. };
  175. modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
  176. modelBuilder.Configurations.AddFromAssembly(typeof(RHDWContext).Assembly);//自动加载Entity-Type
  177. var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<RHDWContext>(modelBuilder);
  178. Database.SetInitializer(sqliteConnectionInitializer);
  179. base.OnModelCreating(modelBuilder);
  180. }
  181. public DbSet<XlInfo> XlInfos { set; get; }
  182. public DbSet<TaskInfo> TaskInfos { set; get; }
  183. public DbSet<TaskSig> TaskSigs { set; get; }
  184. public DbSet<TxInfo> TxInfos { get; set; }
  185. public DbSet<SatInfo> SatInfos { get; set; }
  186. public DbSet<FixedStation> FixedStation { get; set; }
  187. public DbSet<SigInfo> SigInfos { get; set; }
  188. public DbSet<SigDelay> SigDelays { get; set; }
  189. public DbSet<TargetInfo> TargetInfos { get; set; }
  190. public DbSet<SysSetings> SysSetings { get; set; }
  191. }
  192. /// <summary>
  193. /// 分区表上下文(id为long)
  194. /// </summary>
  195. public class RHDWPartContext : DbContext
  196. {
  197. private string DbFile;
  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. var dbFile = Database.Connection.ConnectionString.Replace("Data Source=", "").Replace("|DataDirectory|\\", "");
  224. this.DbFile = dbFile;
  225. }
  226. public string CheckTableField()
  227. {
  228. var tables = this.Database.SqlQuery<string>("select name from sqlite_master where type='table' and name not like 'sqlite%'").ToList();
  229. var props = this.GetType().GetProperties();
  230. List<Type> entityTypes = new List<Type>();
  231. foreach (var prop in props)
  232. {
  233. bool isDbSet = prop.PropertyType.IsGenericType && typeof(DbSet<>) == prop.PropertyType.GetGenericTypeDefinition();
  234. if (isDbSet)
  235. {
  236. var entityType = prop.PropertyType.GenericTypeArguments[0];
  237. entityTypes.Add(entityType);
  238. }
  239. }
  240. foreach (var table in tables)
  241. {
  242. var res = this.Database.SqlQuery<DbTableColumnInfo>($"PRAGMA table_info([{table}])").ToList();
  243. var entityType = entityTypes.First(p => p.Name == table);
  244. var entityProps = entityType.GetProperties().Where(p =>
  245. p.CanRead
  246. && p.CanWrite
  247. && !p.GetMethod.IsVirtual
  248. && p.GetCustomAttribute<NotMappedAttribute>() == null);
  249. foreach (var prop in entityProps)
  250. {
  251. var find = res.Find(p => p.name == prop.Name);
  252. if (find == null)
  253. {
  254. string typeStr = "";
  255. var type = prop.PropertyType;
  256. if (prop.PropertyType.IsGenericType)
  257. {
  258. type = prop.PropertyType.GenericTypeArguments[0];
  259. }
  260. if (type == typeof(string))
  261. {
  262. typeStr = "nvarchar";
  263. }
  264. else if (type == typeof(int) || type == typeof(long))
  265. {
  266. typeStr = "int";
  267. }
  268. else if (type == typeof(double) || type == typeof(float))
  269. {
  270. typeStr = "float";
  271. }
  272. else if (type == typeof(DateTime))
  273. {
  274. typeStr = "datetime";
  275. }
  276. return $"{DbFile}数据库表{table}缺少{prop.Name}字段,类型={typeStr}";
  277. }
  278. else
  279. {
  280. if (prop.PropertyType != typeof(string) && find.pk == 0 && !prop.PropertyType.IsGenericType && find.notnull == 0)
  281. {
  282. var foreignInfo = this.Database.SqlQuery<DbTableForeignKeyInfo>($"PRAGMA foreign_key_list({table})").ToList();
  283. if (!foreignInfo.Any(p => p.from == prop.Name))
  284. {
  285. return $"{DbFile}数据库表{table}中{prop.Name}字段不允许为空";
  286. }
  287. }
  288. }
  289. }
  290. }
  291. return "";
  292. }
  293. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  294. {
  295. this.Database.Log = msg =>
  296. {
  297. };
  298. modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
  299. modelBuilder.Configurations.AddFromAssembly(typeof(RHDWPartContext).Assembly);
  300. var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<RHDWPartContext>(modelBuilder);
  301. Database.SetInitializer(sqliteConnectionInitializer);
  302. base.OnModelCreating(modelBuilder);
  303. }
  304. public DbSet<StationRes> StationRes { get; set; }
  305. public DbSet<CxRes> CxRes { get; set; }
  306. public DbSet<CgRes> CgRes { get; set; }
  307. public DbSet<CgXgfRes> CgXgfRes { get; set; }
  308. public DbSet<PosRes> PosRes { get; set; }
  309. public DbSet<CheckRes> CheckRes { get; set; }
  310. }
  311. public class SqliteConfiguration : DbConfiguration
  312. {
  313. public SqliteConfiguration()
  314. {
  315. DbInterception.Add(new SqliteInterceptor());//拦截器
  316. SetProviderFactory("System.Data.SQLite", SQLiteFactory.Instance);
  317. SetProviderFactory("System.Data.SQLite.EF6", SQLiteProviderFactory.Instance);
  318. SetProviderServices("System.Data.SQLite", (DbProviderServices)SQLiteProviderFactory.Instance.GetService(typeof(DbProviderServices)));
  319. }
  320. }
  321. }