123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422 |
- using MainForm.Common;
- using Newtonsoft.Json;
- using SqlSugar;
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- namespace MainForm.DbHelper
- {
- /// <summary>
- /// 连接
- /// </summary>
- public class PracticeContext
- {
- //private static readonly string _connectionString = ConfigurationManager.AppSettings["DefaultConnection"];
- /// <summary>
- ///
- /// </summary>
- public SqlSugarClient Db;
- /// <summary>
- /// 初始化
- /// </summary>
- /// <param name="connName">连接字符串名称</param>
- public PracticeContext()
- {
- Db = new SqlSugarClient(new ConnectionConfig()
- {
- //ConnectionString = AESEncryptHelper.Decode(_connectionString,AESEncryptHelper.EncryptKey), // 连接字符串
- ConnectionString = @"server= " + GlobalContext.Server +
- ";database= DBMain" +
- ";uid=" + GlobalContext.User +
- ";pwd=" + GlobalContext.PassWord,
- DbType = DbType.SqlServer, // 数据库类型
- InitKeyType = InitKeyType.Attribute, // 从特性读取主键和自增列信息
- IsAutoCloseConnection = true // 开启自动释放模式,和EF原理一样
- }) ;
- //// 每次Sql执行前事件,记录进行的操作
- //Db.Aop.OnLogExecuting = (sql, pars) =>
- //{
- // StringBuilder sqlStr = new();
- // if (sql.StartsWith("UPDATE") || sql.StartsWith("INSERT"))
- // {
- // Console.ForegroundColor = ConsoleColor.Blue;
- // sqlStr.AppendLine($"==============将要执行新增/修改操作==============");
- // }
- // if (sql.StartsWith("DELETE"))
- // {
- // Console.ForegroundColor = ConsoleColor.Red;
- // sqlStr.AppendLine($"==============将要执行删除操作==============");
- // }
- // if (sql.StartsWith("SELECT"))
- // {
- // Console.ForegroundColor = ConsoleColor.Green;
- // sqlStr.AppendLine($"==============将要执行查询操作==============");
- // }
- // sqlStr.AppendLine("预SQL:");
- // sqlStr.AppendLine(" " + sql);
- // string sqlPars = Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value));
- // sqlStr.AppendLine("SQL预传参:");
- // sqlStr.AppendLine(" " + sqlPars);
- // Console.WriteLine(sqlStr.ToString()); // 打印
- // Console.ForegroundColor = ConsoleColor.White;
- // // 记录执行的信息
- //};
- ////每次Sql执行后事件,记录SQL执行完的信息
- //Db.Aop.OnLogExecuted = (sql, pars) =>
- //{
- // // 执行时间超过1秒
- // if (Db.Ado.SqlExecutionTime.TotalSeconds > 1)
- // {
- // StringBuilder sqlPStr = new();
- // sqlPStr.AppendLine($"==============执行了下面的操作==============");
- // var fileName = Db.Ado.SqlStackTrace.FirstFileName; // 代码CS文件名
- // sqlPStr.AppendLine("代码CS文件名:" + fileName);
- // var fileLine = Db.Ado.SqlStackTrace.FirstLine; // 代码行数
- // sqlPStr.AppendLine("代码行数:" + fileLine);
- // var FirstMethodName = Db.Ado.SqlStackTrace.FirstMethodName; // 方法名
- // sqlPStr.AppendLine("方法名:" + FirstMethodName);
- // sqlPStr.AppendLine("SQL:");
- // sqlPStr.AppendLine(" " + sql);
- // var sqlPars = Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)); // 参数
- // sqlPStr.AppendLine("SQL传参:");
- // sqlPStr.AppendLine(" " + sqlPars);
- // // 打印
- // Console.ForegroundColor = ConsoleColor.Green;
- // Console.WriteLine(sqlPStr);
- // Console.ForegroundColor = ConsoleColor.White;
- // // 记录执行的信息
- // }
- //};
- //// 记录SQL报错
- //Db.Aop.OnError = (exp) =>
- //{
- // StringBuilder sqlStr = new();
- // sqlStr.AppendLine($"==============数据库执行报错==============");
- // sqlStr.AppendLine("SQL: ");
- // sqlStr.AppendLine(" " + exp.Sql);
- // Console.ForegroundColor = ConsoleColor.Red;
- // Console.WriteLine(sqlStr); // 打印
- // Console.ForegroundColor = ConsoleColor.White;
- // // 记录执行的信息
- //};
- }
- /// <summary>
- /// 初始化
- /// </summary>
- /// <param name="connName">连接字符串名称</param>
- public PracticeContext(string connectionString)
- {
- Db = new SqlSugarClient(new ConnectionConfig()
- {
- ConnectionString = connectionString, // 连接字符串
- DbType = DbType.SqlServer, // 数据库类型
- InitKeyType = InitKeyType.Attribute, // 从特性读取主键和自增列信息
- IsAutoCloseConnection = true // 开启自动释放模式,和EF原理一样
- });
- //// 每次Sql执行前事件,记录进行的操作
- //Db.Aop.OnLogExecuting = (sql, pars) =>
- //{
- // StringBuilder sqlStr = new();
- // if (sql.StartsWith("UPDATE") || sql.StartsWith("INSERT"))
- // {
- // Console.ForegroundColor = ConsoleColor.Blue;
- // sqlStr.AppendLine($"==============将要执行新增/修改操作==============");
- // }
- // if (sql.StartsWith("DELETE"))
- // {
- // Console.ForegroundColor = ConsoleColor.Red;
- // sqlStr.AppendLine($"==============将要执行删除操作==============");
- // }
- // if (sql.StartsWith("SELECT"))
- // {
- // Console.ForegroundColor = ConsoleColor.Green;
- // sqlStr.AppendLine($"==============将要执行查询操作==============");
- // }
- // sqlStr.AppendLine("预SQL:");
- // sqlStr.AppendLine(" " + sql);
- // string sqlPars = Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value));
- // sqlStr.AppendLine("SQL预传参:");
- // sqlStr.AppendLine(" " + sqlPars);
- // Console.WriteLine(sqlStr.ToString()); // 打印
- // Console.ForegroundColor = ConsoleColor.White;
- // // 记录执行的信息
- //};
- ////每次Sql执行后事件,记录SQL执行完的信息
- //Db.Aop.OnLogExecuted = (sql, pars) =>
- //{
- // // 执行时间超过1秒
- // if (Db.Ado.SqlExecutionTime.TotalSeconds > 1)
- // {
- // StringBuilder sqlPStr = new();
- // sqlPStr.AppendLine($"==============执行了下面的操作==============");
- // var fileName = Db.Ado.SqlStackTrace.FirstFileName; // 代码CS文件名
- // sqlPStr.AppendLine("代码CS文件名:" + fileName);
- // var fileLine = Db.Ado.SqlStackTrace.FirstLine; // 代码行数
- // sqlPStr.AppendLine("代码行数:" + fileLine);
- // var FirstMethodName = Db.Ado.SqlStackTrace.FirstMethodName; // 方法名
- // sqlPStr.AppendLine("方法名:" + FirstMethodName);
- // sqlPStr.AppendLine("SQL:");
- // sqlPStr.AppendLine(" " + sql);
- // var sqlPars = Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)); // 参数
- // sqlPStr.AppendLine("SQL传参:");
- // sqlPStr.AppendLine(" " + sqlPars);
- // // 打印
- // Console.ForegroundColor = ConsoleColor.Green;
- // Console.WriteLine(sqlPStr);
- // Console.ForegroundColor = ConsoleColor.White;
- // // 记录执行的信息
- // }
- //};
- //// 记录SQL报错
- //Db.Aop.OnError = (exp) =>
- //{
- // StringBuilder sqlStr = new();
- // sqlStr.AppendLine($"==============数据库执行报错==============");
- // sqlStr.AppendLine("SQL: ");
- // sqlStr.AppendLine(" " + exp.Sql);
- // Console.ForegroundColor = ConsoleColor.Red;
- // Console.WriteLine(sqlStr); // 打印
- // Console.ForegroundColor = ConsoleColor.White;
- // // 记录执行的信息
- //};
- }
- /// <summary>
- /// 根据Entity(实体)生成数据库中的表
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="entity">指定Entity名;不指定时生成指定作用域中/默认作用域(一般指文件夹名)下所有Entity的表结构</param>
- /// <param name="dllName">指定类的包名</param>
- /// <param name="classNameSpaces">指定类的包名</param>
- public void CodeFirst<T>(T entity = null, string dllName = "BOZHON.Repository.dll", string[] classNameSpaces = null) where T : class, new()
- {
- classNameSpaces = classNameSpaces == null ? new string[] { "Entity" } : classNameSpaces;
- if (entity is null)
- {
- var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
- List<Type> entitylist = new List<Type>();
- if (!string.IsNullOrWhiteSpace(dllName))
- {
- dllName = path + dllName;
- Assembly assembly = Assembly.LoadFrom(dllName);
- Type[] ts = assembly.GetTypes();
- foreach (string classNameSpace in classNameSpaces)
- {
- foreach (Type t in ts)
- {
- if (t.FullName.Contains(classNameSpace))
- {
- entitylist.Add(t);
- }
- }
- }
- }
- Db.CodeFirst.SetStringDefaultLength(255).InitTables(entitylist.ToArray());
- }
- else
- {
- Db.CodeFirst.SetStringDefaultLength(255).InitTables(typeof(T));
- }
- }
- /// <summary>
- /// 导入种子数据
- /// 注:批量不可用(指定Entity名时功能可用,通过“classNameSpaces”批量导入时功能不可用)
- /// ① DBSeed文件使用json文件保存;
- /// ② 一张表一个DBSeed文件;
- /// ③ 文件名字与表名保持一致;
- /// </summary>
- /// <param name="dbSeedFileDirec">DB种子数据所在的的文件夹(放在程序目录下)</param>
- /// <typeparam name="T"></typeparam>
- /// <param name="entity">指定Entity名;不指定时生成指定作用域中/默认作用域(一般指文件夹名)下所有Entity的表的数据</param>
- /// <param name="dllName">指定实体类的包名</param>
- /// <param name="classNameSpaces">指定实体类的包名</param>
- /// <exception cref="NotImplementedException"></exception>
- public void ImportDBSeed<T>(string dbSeedFileDirec, T entity = null, string dllName = "BOZHON.Repository.dll", string[] classNameSpaces = null) where T : class, new()
- {
- classNameSpaces = classNameSpaces == null ? new string[] { "Entity" } : classNameSpaces;
- var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
- string dbSeedFileDirecPath = path + dbSeedFileDirec + @"/";
- if (!Directory.Exists(dbSeedFileDirecPath))
- {
- throw new Exception("DB数据初始化失败!在程序目录下找不到DB种子数据文件夹!");
- }
- if (entity is null)
- {
- List<Type> entitylist = new List<Type>();
- if (!string.IsNullOrWhiteSpace(dllName))
- {
- dllName = path + dllName;
- Assembly assembly = Assembly.LoadFrom(dllName);
- Type[] ts = assembly.GetTypes();
- foreach (string classNameSpace in classNameSpaces)
- {
- foreach (Type t in ts)
- {
- if (t.FullName.Contains(classNameSpace))
- {
- entitylist.Add(t);
- }
- }
- }
- }
- foreach (Type type in entitylist)
- {
- string dbSeedFilePath = dbSeedFileDirecPath + type.Name + ".json";
- if (File.Exists(dbSeedFilePath))
- {
- Type typeList = typeof(List<>);
- Type actualType = typeList.MakeGenericType(type);
- dynamic obj = Activator.CreateInstance(actualType);
- obj = JsonFileHelper.ReadjsonT<object>(dbSeedFilePath); // 加载数据
- //Db.Insertable(obj).ExecuteCommand(); // 未找到合适的无实体插入方法
- throw new Exception("批量插入请使用方法ImportDBSeed2!");
- }
- }
- }
- else
- {
- string dbSeedFilePath = dbSeedFileDirecPath + entity.GetType().Name + ".json";
- if (File.Exists(dbSeedFilePath))
- {
- T obj = JsonFileHelper.ReadjsonT<T>(dbSeedFilePath); // 加载数据
- Db.Insertable(obj);
- }
- }
- }
- /// <summary>
- /// 导入种子数据-批量
- /// ① DBSeed文件使用json文件保存;
- /// ② 一张表一个DBSeed文件;
- /// ③ 文件名字与表名保持一致;
- /// </summary>
- /// <param name="dbSeedFileDirec">DB种子数据所在的的文件夹(放在程序目录下)</param>
- /// <typeparam name="T"></typeparam>
- /// <param name="entity">指定Entity名;不指定时生成指定作用域中/默认作用域(一般指文件夹名)下所有Entity的表的数据</param>
- /// <param name="dllName">指定实体类的包名</param>
- /// <param name="classNameSpaces">指定实体类的包名</param>
- /// <exception cref="NotImplementedException"></exception>
- public void ImportDBSeed2(string dbSeedFileDirec)
- {
- var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
- string dbSeedFileDirecPath = path + dbSeedFileDirec + @"/";
- if (!Directory.Exists(dbSeedFileDirecPath))
- {
- throw new Exception("DB数据初始化失败!在程序目录下找不到DB种子数据文件夹!");
- }
- #region 设置DBSeed
- //ImportDBSeed2<SYS_USER>(dbSeedFileDirecPath);
- //ImportDBSeed2<SYS_USER_ROLE>(dbSeedFileDirecPath);
- #endregion 设置DBSeed
- }
- /// <summary>
- /// ImportDBSeed2-导入种子数据
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="dbSeedFileDirecPath">文件夹路径</param>
- private void ImportDBSeed2<T>(string dbSeedFileDirecPath) where T : class, new()
- {
- string dbSeedFilePath = dbSeedFileDirecPath + new T().GetType().Name + ".json";
- if (File.Exists(dbSeedFilePath))
- {
- var objs = JsonFileHelper.ReadjsonT<List<T>>(dbSeedFilePath); // 加载数据
- Db.Insertable<T>(objs).ExecuteCommand();
- }
- }
- /// <summary>
- /// 导出种子数据
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="dbSeedFileDirec">DB种子数据导出的文件夹(生成在程序目录下)</param>
- /// <param name="entity">指定Entity名;不指定时生成指定作用域中/默认作用域(一般指文件夹名)下所有Entity的表的数据</param>
- /// <param name="dllName">指定实体类的包名</param>
- /// <param name="classNameSpaces">指定实体类的包名</param>
- public void ExportDBSeed<T>(string dbSeedFileDirec, T entity = null, string dllName = "BOZHON.Repository.dll", string[] classNameSpaces = null) where T : class, new()
- {
- classNameSpaces = classNameSpaces == null ? new string[] { "Entity" } : classNameSpaces;
- var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
- string dbSeedFileDirecPath = path + dbSeedFileDirec + @"/";
- if (!Directory.Exists(dbSeedFileDirecPath))
- {
- Directory.CreateDirectory(dbSeedFileDirecPath); // 生成目录
- }
- if (entity is null)
- {
- List<Type> entitylist = new List<Type>();
- if (!string.IsNullOrWhiteSpace(dllName))
- {
- dllName = path + dllName;
- Assembly assembly = Assembly.LoadFrom(dllName);
- Type[] ts = assembly.GetTypes();
- foreach (string classNameSpace in classNameSpaces)
- {
- foreach (Type t in ts)
- {
- if (t.FullName.Contains(classNameSpace))
- {
- entitylist.Add(t);
- }
- }
- }
- }
- foreach (Type type in entitylist)
- {
- string dbSeedFilePath = dbSeedFileDirecPath + type.Name + ".json";
- var seedDatas = Db.Queryable(type.Name, type.Name).ToList();
- JsonFileHelper.WritejsonT(dbSeedFilePath, seedDatas);
- }
- }
- else
- {
- string dbSeedFilePath = dbSeedFileDirecPath + entity.GetType().Name + ".json";
- var seedDatas = Db.Queryable<T>().ToList();
- JsonFileHelper.WritejsonT(dbSeedFilePath, seedDatas);
- }
- }
- }
- }
|