123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345 |
- using SQLite.CodeFirst;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.Data.Common;
- using System.Data.Entity;
- using System.Data.Entity.Core.Common;
- using System.Data.Entity.Infrastructure;
- using System.Data.Entity.Infrastructure.Interception;
- using System.Data.Entity.ModelConfiguration.Conventions;
- using System.Data.Entity.Validation;
- using System.Data.SQLite;
- using System.Data.SQLite.EF6;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Text.RegularExpressions;
- using System.Threading.Tasks;
- using XdCxRhDW.Entity;
- namespace XdCxRhDW.Repostory
- {
- class DbTableColumnInfo
- {
- public string name { get; set; }
- public string type { get; set; }
- public int notnull { get; set; }
- public int pk { get; set; }
- }
- class DbTableForeignKeyInfo
- {
- public string from { get; set; }
- }
- public class RHDWLogContext : DbContext
- {
- public string DbFile;
- public RHDWLogContext() : base("LogDbCon") //配置使用的连接名
- {
- //|DataDirectory|在mvc等程序中代表了App_Data,在普通程序中代表程序根目录
- var dbFile = Database.Connection.ConnectionString.Replace("Data Source=", "").Replace("|DataDirectory|\\", "");
- this.DbFile = dbFile;
- }
- protected override void OnModelCreating(DbModelBuilder modelBuilder)
- {
- this.Database.Log = msg =>
- {
- };
- modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
- modelBuilder.Configurations.AddFromAssembly(typeof(RHDWLogContext).Assembly);//自动加载Entity-Type
- var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<RHDWLogContext>(modelBuilder);
- Database.SetInitializer(sqliteConnectionInitializer);
- base.OnModelCreating(modelBuilder);
- }
- public DbSet<LogRes> LogRes { set; get; }
- }
- /// <summary>
- /// 基础表上下文(id为int)
- /// </summary>
- public class RHDWContext : DbContext
- {
- public string DbFile;
- public RHDWContext() : base("DbCon") //配置使用的连接名
- {
- //|DataDirectory|在mvc等程序中代表了App_Data,在普通程序中代表程序根目录
- this.DbFile = Database.Connection.ConnectionString.Replace("Data Source=", "").Replace("|DataDirectory|\\", "");
- }
- public Task<List<T>> SqlQueryAsync<T>(string sql)
- {
- return this.Database.SqlQuery<T>(sql).ToListAsync();
- }
- public Task<T> SqlQueryOneAsync<T>(string sql)
- {
- return this.Database.SqlQuery<T>(sql).FirstOrDefaultAsync();
- }
- //检查数据库表是否缺失
- public string CheckTableExist()
- {
- var tables = this.Database.SqlQuery<string>("select name from sqlite_master where type='table' and name not like 'sqlite%'").ToList();
- var props = this.GetType().GetProperties();
- List<string> list = new List<string>();
- foreach (var prop in props)
- {
- bool isDbSet = prop.PropertyType.IsGenericType && typeof(DbSet<>) == prop.PropertyType.GetGenericTypeDefinition();
- if (isDbSet)
- {
- var entityType = prop.PropertyType.GenericTypeArguments[0];
- var name = entityType.GetCustomAttribute<TableAttribute>()?.Name;
- if (name == null)
- {
- name = entityType.Name;
- }
- list.Add(name);
- }
- }
- foreach (var item in list)
- {
- if (!tables.Contains(item))
- {
- return item;
- }
- }
- return "";
- }
- public string CheckTableField()
- {
- var tables = this.Database.SqlQuery<string>("select name from sqlite_master where type='table' and name not like 'sqlite%'").ToList();
- var props = this.GetType().GetProperties();
- List<Type> entityTypes = new List<Type>();
- foreach (var prop in props)
- {
- bool isDbSet = prop.PropertyType.IsGenericType && typeof(DbSet<>) == prop.PropertyType.GetGenericTypeDefinition();
- if (isDbSet)
- {
- var entityType = prop.PropertyType.GenericTypeArguments[0];
- entityTypes.Add(entityType);
- }
- }
- foreach (var table in tables)
- {
- var res = this.Database.SqlQuery<DbTableColumnInfo>($"PRAGMA table_info([{table}])").ToList();
- var entityType = entityTypes.First(p => p.Name == table);
- var entityProps = entityType.GetProperties().Where(p =>
- p.CanRead
- && p.CanWrite
- && !p.GetMethod.IsVirtual
- && p.GetCustomAttribute<NotMappedAttribute>() == null);
- foreach (var prop in entityProps)
- {
- var find = res.Find(p => p.name == prop.Name);
- if (find == null)
- {
- string typeStr = "";
- var type = prop.PropertyType;
- if (prop.PropertyType.IsGenericType)
- {
- type = prop.PropertyType.GenericTypeArguments[0];
- }
- if (type == typeof(string))
- {
- typeStr = "nvarchar";
- }
- else if (type == typeof(int) || type == typeof(long))
- {
- typeStr = "int";
- }
- else if (type == typeof(double) || type == typeof(float))
- {
- typeStr = "float";
- }
- else if (type == typeof(DateTime))
- {
- typeStr = "datetime";
- }
- return $"{DbFile}数据库表{table}缺少{prop.Name}字段,类型={typeStr}";
- }
- else
- {
- if (prop.PropertyType != typeof(string) && find.pk == 0 && !prop.PropertyType.IsGenericType && find.notnull == 0)
- {
- var foreignInfo = this.Database.SqlQuery<DbTableForeignKeyInfo>($"PRAGMA foreign_key_list({table})").ToList();
- if (!foreignInfo.Any(p => p.from == prop.Name))
- {
- return $"{DbFile}数据库表{table}中{prop.Name}字段不允许为空";
- }
- }
- }
- }
- }
- return "";
- }
- protected override void OnModelCreating(DbModelBuilder modelBuilder)
- {
- this.Database.Log = msg =>
- {
- };
- modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
- modelBuilder.Configurations.AddFromAssembly(typeof(RHDWContext).Assembly);//自动加载Entity-Type
- var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<RHDWContext>(modelBuilder);
- Database.SetInitializer(sqliteConnectionInitializer);
- base.OnModelCreating(modelBuilder);
- }
- public DbSet<XlInfo> XlInfos { set; get; }
- public DbSet<TaskInfo> TaskInfos { set; get; }
- public DbSet<TaskSig> TaskSigs { set; get; }
- public DbSet<TxInfo> TxInfos { get; set; }
- public DbSet<SatInfo> SatInfos { get; set; }
- public DbSet<FixedStation> FixedStation { get; set; }
- public DbSet<SigInfo> SigInfos { get; set; }
- public DbSet<SigDelay> SigDelays { get; set; }
- public DbSet<TargetInfo> TargetInfos { get; set; }
- public DbSet<SysSetings> SysSetings { get; set; }
- }
- /// <summary>
- /// 分区表上下文(id为long)
- /// </summary>
- public class RHDWPartContext : DbContext
- {
- private string DbFile;
- public static RHDWPartContext GetContext(string dbFile, bool createDb = false)
- {
- if (!File.Exists(dbFile) && !createDb)
- {
- return null;
- }
- var connectionString = $@"Data Source={dbFile}";
- SQLiteConnection con = new SQLiteConnection(connectionString);
- return new RHDWPartContext(con);
- }
- public static RHDWPartContext GetContext(DateTime partTime, bool createDb = false, string prefix = "")
- {
- var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DbPart");
- var dayFile = Path.Combine(dir, $@"{partTime.Year}\{prefix}{partTime:MMdd}.db");
- if (!File.Exists(dayFile) && !createDb)
- {
- return null;
- }
- var connectionString = $@"Data Source=|DataDirectory|\DbPart\{partTime.Year}\{prefix}{partTime:MMdd}.db";
- SQLiteConnection con = new SQLiteConnection(connectionString);
- return new RHDWPartContext(con);
- }
- private RHDWPartContext(DbConnection con)
- : base(con, true)
- {
- var dbFile = Database.Connection.ConnectionString.Replace("Data Source=", "").Replace("|DataDirectory|\\", "");
- this.DbFile = dbFile;
- }
- public string CheckTableField()
- {
- var tables = this.Database.SqlQuery<string>("select name from sqlite_master where type='table' and name not like 'sqlite%'").ToList();
- var props = this.GetType().GetProperties();
- List<Type> entityTypes = new List<Type>();
- foreach (var prop in props)
- {
- bool isDbSet = prop.PropertyType.IsGenericType && typeof(DbSet<>) == prop.PropertyType.GetGenericTypeDefinition();
- if (isDbSet)
- {
- var entityType = prop.PropertyType.GenericTypeArguments[0];
- entityTypes.Add(entityType);
- }
- }
- foreach (var table in tables)
- {
- var res = this.Database.SqlQuery<DbTableColumnInfo>($"PRAGMA table_info([{table}])").ToList();
- var entityType = entityTypes.First(p => p.Name == table);
- var entityProps = entityType.GetProperties().Where(p =>
- p.CanRead
- && p.CanWrite
- && !p.GetMethod.IsVirtual
- && p.GetCustomAttribute<NotMappedAttribute>() == null);
- foreach (var prop in entityProps)
- {
- var find = res.Find(p => p.name == prop.Name);
- if (find == null)
- {
- string typeStr = "";
- var type = prop.PropertyType;
- if (prop.PropertyType.IsGenericType)
- {
- type = prop.PropertyType.GenericTypeArguments[0];
- }
- if (type == typeof(string))
- {
- typeStr = "nvarchar";
- }
- else if (type == typeof(int) || type == typeof(long))
- {
- typeStr = "int";
- }
- else if (type == typeof(double) || type == typeof(float))
- {
- typeStr = "float";
- }
- else if (type == typeof(DateTime))
- {
- typeStr = "datetime";
- }
- return $"{DbFile}数据库表{table}缺少{prop.Name}字段,类型={typeStr}";
- }
- else
- {
- if (prop.PropertyType != typeof(string) && find.pk == 0 && !prop.PropertyType.IsGenericType && find.notnull == 0)
- {
- var foreignInfo = this.Database.SqlQuery<DbTableForeignKeyInfo>($"PRAGMA foreign_key_list({table})").ToList();
- if (!foreignInfo.Any(p => p.from == prop.Name))
- {
- return $"{DbFile}数据库表{table}中{prop.Name}字段不允许为空";
- }
- }
- }
- }
- }
- return "";
- }
- protected override void OnModelCreating(DbModelBuilder modelBuilder)
- {
- this.Database.Log = msg =>
- {
- };
- modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
- modelBuilder.Configurations.AddFromAssembly(typeof(RHDWPartContext).Assembly);
- var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<RHDWPartContext>(modelBuilder);
- Database.SetInitializer(sqliteConnectionInitializer);
- base.OnModelCreating(modelBuilder);
- }
- public DbSet<StationRes> StationRes { get; set; }
- public DbSet<CxRes> CxRes { get; set; }
- public DbSet<CgRes> CgRes { get; set; }
- public DbSet<CgXgfRes> CgXgfRes { get; set; }
- public DbSet<PosRes> PosRes { get; set; }
- public DbSet<CheckRes> CheckRes { get; set; }
- }
- public class SqliteConfiguration : DbConfiguration
- {
- public SqliteConfiguration()
- {
- DbInterception.Add(new SqliteInterceptor());//拦截器
- SetProviderFactory("System.Data.SQLite", SQLiteFactory.Instance);
- SetProviderFactory("System.Data.SQLite.EF6", SQLiteProviderFactory.Instance);
- SetProviderServices("System.Data.SQLite", (DbProviderServices)SQLiteProviderFactory.Instance.GetService(typeof(DbProviderServices)));
- }
- }
- }
|