PracticeContext.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. using MainForm.Common;
  2. using Newtonsoft.Json;
  3. using SqlSugar;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Configuration;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Reflection;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. namespace MainForm.DbHelper
  13. {
  14. /// <summary>
  15. /// 连接
  16. /// </summary>
  17. public class PracticeContext
  18. {
  19. //private static readonly string _connectionString = ConfigurationManager.AppSettings["DefaultConnection"];
  20. /// <summary>
  21. ///
  22. /// </summary>
  23. public SqlSugarClient Db;
  24. /// <summary>
  25. /// 初始化
  26. /// </summary>
  27. /// <param name="connName">连接字符串名称</param>
  28. public PracticeContext()
  29. {
  30. Db = new SqlSugarClient(new ConnectionConfig()
  31. {
  32. //ConnectionString = AESEncryptHelper.Decode(_connectionString,AESEncryptHelper.EncryptKey), // 连接字符串
  33. ConnectionString = @"server= " + GlobalContext.Server +
  34. ";database= DBMain" +
  35. ";uid=" + GlobalContext.User +
  36. ";pwd=" + GlobalContext.PassWord,
  37. DbType = DbType.SqlServer, // 数据库类型
  38. InitKeyType = InitKeyType.Attribute, // 从特性读取主键和自增列信息
  39. IsAutoCloseConnection = true // 开启自动释放模式,和EF原理一样
  40. }) ;
  41. //// 每次Sql执行前事件,记录进行的操作
  42. //Db.Aop.OnLogExecuting = (sql, pars) =>
  43. //{
  44. // StringBuilder sqlStr = new();
  45. // if (sql.StartsWith("UPDATE") || sql.StartsWith("INSERT"))
  46. // {
  47. // Console.ForegroundColor = ConsoleColor.Blue;
  48. // sqlStr.AppendLine($"==============将要执行新增/修改操作==============");
  49. // }
  50. // if (sql.StartsWith("DELETE"))
  51. // {
  52. // Console.ForegroundColor = ConsoleColor.Red;
  53. // sqlStr.AppendLine($"==============将要执行删除操作==============");
  54. // }
  55. // if (sql.StartsWith("SELECT"))
  56. // {
  57. // Console.ForegroundColor = ConsoleColor.Green;
  58. // sqlStr.AppendLine($"==============将要执行查询操作==============");
  59. // }
  60. // sqlStr.AppendLine("预SQL:");
  61. // sqlStr.AppendLine(" " + sql);
  62. // string sqlPars = Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value));
  63. // sqlStr.AppendLine("SQL预传参:");
  64. // sqlStr.AppendLine(" " + sqlPars);
  65. // Console.WriteLine(sqlStr.ToString()); // 打印
  66. // Console.ForegroundColor = ConsoleColor.White;
  67. // // 记录执行的信息
  68. //};
  69. ////每次Sql执行后事件,记录SQL执行完的信息
  70. //Db.Aop.OnLogExecuted = (sql, pars) =>
  71. //{
  72. // // 执行时间超过1秒
  73. // if (Db.Ado.SqlExecutionTime.TotalSeconds > 1)
  74. // {
  75. // StringBuilder sqlPStr = new();
  76. // sqlPStr.AppendLine($"==============执行了下面的操作==============");
  77. // var fileName = Db.Ado.SqlStackTrace.FirstFileName; // 代码CS文件名
  78. // sqlPStr.AppendLine("代码CS文件名:" + fileName);
  79. // var fileLine = Db.Ado.SqlStackTrace.FirstLine; // 代码行数
  80. // sqlPStr.AppendLine("代码行数:" + fileLine);
  81. // var FirstMethodName = Db.Ado.SqlStackTrace.FirstMethodName; // 方法名
  82. // sqlPStr.AppendLine("方法名:" + FirstMethodName);
  83. // sqlPStr.AppendLine("SQL:");
  84. // sqlPStr.AppendLine(" " + sql);
  85. // var sqlPars = Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)); // 参数
  86. // sqlPStr.AppendLine("SQL传参:");
  87. // sqlPStr.AppendLine(" " + sqlPars);
  88. // // 打印
  89. // Console.ForegroundColor = ConsoleColor.Green;
  90. // Console.WriteLine(sqlPStr);
  91. // Console.ForegroundColor = ConsoleColor.White;
  92. // // 记录执行的信息
  93. // }
  94. //};
  95. //// 记录SQL报错
  96. //Db.Aop.OnError = (exp) =>
  97. //{
  98. // StringBuilder sqlStr = new();
  99. // sqlStr.AppendLine($"==============数据库执行报错==============");
  100. // sqlStr.AppendLine("SQL: ");
  101. // sqlStr.AppendLine(" " + exp.Sql);
  102. // Console.ForegroundColor = ConsoleColor.Red;
  103. // Console.WriteLine(sqlStr); // 打印
  104. // Console.ForegroundColor = ConsoleColor.White;
  105. // // 记录执行的信息
  106. //};
  107. }
  108. /// <summary>
  109. /// 初始化
  110. /// </summary>
  111. /// <param name="connName">连接字符串名称</param>
  112. public PracticeContext(string connectionString)
  113. {
  114. Db = new SqlSugarClient(new ConnectionConfig()
  115. {
  116. ConnectionString = connectionString, // 连接字符串
  117. DbType = DbType.SqlServer, // 数据库类型
  118. InitKeyType = InitKeyType.Attribute, // 从特性读取主键和自增列信息
  119. IsAutoCloseConnection = true // 开启自动释放模式,和EF原理一样
  120. });
  121. //// 每次Sql执行前事件,记录进行的操作
  122. //Db.Aop.OnLogExecuting = (sql, pars) =>
  123. //{
  124. // StringBuilder sqlStr = new();
  125. // if (sql.StartsWith("UPDATE") || sql.StartsWith("INSERT"))
  126. // {
  127. // Console.ForegroundColor = ConsoleColor.Blue;
  128. // sqlStr.AppendLine($"==============将要执行新增/修改操作==============");
  129. // }
  130. // if (sql.StartsWith("DELETE"))
  131. // {
  132. // Console.ForegroundColor = ConsoleColor.Red;
  133. // sqlStr.AppendLine($"==============将要执行删除操作==============");
  134. // }
  135. // if (sql.StartsWith("SELECT"))
  136. // {
  137. // Console.ForegroundColor = ConsoleColor.Green;
  138. // sqlStr.AppendLine($"==============将要执行查询操作==============");
  139. // }
  140. // sqlStr.AppendLine("预SQL:");
  141. // sqlStr.AppendLine(" " + sql);
  142. // string sqlPars = Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value));
  143. // sqlStr.AppendLine("SQL预传参:");
  144. // sqlStr.AppendLine(" " + sqlPars);
  145. // Console.WriteLine(sqlStr.ToString()); // 打印
  146. // Console.ForegroundColor = ConsoleColor.White;
  147. // // 记录执行的信息
  148. //};
  149. ////每次Sql执行后事件,记录SQL执行完的信息
  150. //Db.Aop.OnLogExecuted = (sql, pars) =>
  151. //{
  152. // // 执行时间超过1秒
  153. // if (Db.Ado.SqlExecutionTime.TotalSeconds > 1)
  154. // {
  155. // StringBuilder sqlPStr = new();
  156. // sqlPStr.AppendLine($"==============执行了下面的操作==============");
  157. // var fileName = Db.Ado.SqlStackTrace.FirstFileName; // 代码CS文件名
  158. // sqlPStr.AppendLine("代码CS文件名:" + fileName);
  159. // var fileLine = Db.Ado.SqlStackTrace.FirstLine; // 代码行数
  160. // sqlPStr.AppendLine("代码行数:" + fileLine);
  161. // var FirstMethodName = Db.Ado.SqlStackTrace.FirstMethodName; // 方法名
  162. // sqlPStr.AppendLine("方法名:" + FirstMethodName);
  163. // sqlPStr.AppendLine("SQL:");
  164. // sqlPStr.AppendLine(" " + sql);
  165. // var sqlPars = Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)); // 参数
  166. // sqlPStr.AppendLine("SQL传参:");
  167. // sqlPStr.AppendLine(" " + sqlPars);
  168. // // 打印
  169. // Console.ForegroundColor = ConsoleColor.Green;
  170. // Console.WriteLine(sqlPStr);
  171. // Console.ForegroundColor = ConsoleColor.White;
  172. // // 记录执行的信息
  173. // }
  174. //};
  175. //// 记录SQL报错
  176. //Db.Aop.OnError = (exp) =>
  177. //{
  178. // StringBuilder sqlStr = new();
  179. // sqlStr.AppendLine($"==============数据库执行报错==============");
  180. // sqlStr.AppendLine("SQL: ");
  181. // sqlStr.AppendLine(" " + exp.Sql);
  182. // Console.ForegroundColor = ConsoleColor.Red;
  183. // Console.WriteLine(sqlStr); // 打印
  184. // Console.ForegroundColor = ConsoleColor.White;
  185. // // 记录执行的信息
  186. //};
  187. }
  188. /// <summary>
  189. /// 根据Entity(实体)生成数据库中的表
  190. /// </summary>
  191. /// <typeparam name="T"></typeparam>
  192. /// <param name="entity">指定Entity名;不指定时生成指定作用域中/默认作用域(一般指文件夹名)下所有Entity的表结构</param>
  193. /// <param name="dllName">指定类的包名</param>
  194. /// <param name="classNameSpaces">指定类的包名</param>
  195. public void CodeFirst<T>(T entity = null, string dllName = "BOZHON.Repository.dll", string[] classNameSpaces = null) where T : class, new()
  196. {
  197. classNameSpaces = classNameSpaces == null ? new string[] { "Entity" } : classNameSpaces;
  198. if (entity is null)
  199. {
  200. var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
  201. List<Type> entitylist = new List<Type>();
  202. if (!string.IsNullOrWhiteSpace(dllName))
  203. {
  204. dllName = path + dllName;
  205. Assembly assembly = Assembly.LoadFrom(dllName);
  206. Type[] ts = assembly.GetTypes();
  207. foreach (string classNameSpace in classNameSpaces)
  208. {
  209. foreach (Type t in ts)
  210. {
  211. if (t.FullName.Contains(classNameSpace))
  212. {
  213. entitylist.Add(t);
  214. }
  215. }
  216. }
  217. }
  218. Db.CodeFirst.SetStringDefaultLength(255).InitTables(entitylist.ToArray());
  219. }
  220. else
  221. {
  222. Db.CodeFirst.SetStringDefaultLength(255).InitTables(typeof(T));
  223. }
  224. }
  225. /// <summary>
  226. /// 导入种子数据
  227. /// 注:批量不可用(指定Entity名时功能可用,通过“classNameSpaces”批量导入时功能不可用)
  228. /// ① DBSeed文件使用json文件保存;
  229. /// ② 一张表一个DBSeed文件;
  230. /// ③ 文件名字与表名保持一致;
  231. /// </summary>
  232. /// <param name="dbSeedFileDirec">DB种子数据所在的的文件夹(放在程序目录下)</param>
  233. /// <typeparam name="T"></typeparam>
  234. /// <param name="entity">指定Entity名;不指定时生成指定作用域中/默认作用域(一般指文件夹名)下所有Entity的表的数据</param>
  235. /// <param name="dllName">指定实体类的包名</param>
  236. /// <param name="classNameSpaces">指定实体类的包名</param>
  237. /// <exception cref="NotImplementedException"></exception>
  238. public void ImportDBSeed<T>(string dbSeedFileDirec, T entity = null, string dllName = "BOZHON.Repository.dll", string[] classNameSpaces = null) where T : class, new()
  239. {
  240. classNameSpaces = classNameSpaces == null ? new string[] { "Entity" } : classNameSpaces;
  241. var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
  242. string dbSeedFileDirecPath = path + dbSeedFileDirec + @"/";
  243. if (!Directory.Exists(dbSeedFileDirecPath))
  244. {
  245. throw new Exception("DB数据初始化失败!在程序目录下找不到DB种子数据文件夹!");
  246. }
  247. if (entity is null)
  248. {
  249. List<Type> entitylist = new List<Type>();
  250. if (!string.IsNullOrWhiteSpace(dllName))
  251. {
  252. dllName = path + dllName;
  253. Assembly assembly = Assembly.LoadFrom(dllName);
  254. Type[] ts = assembly.GetTypes();
  255. foreach (string classNameSpace in classNameSpaces)
  256. {
  257. foreach (Type t in ts)
  258. {
  259. if (t.FullName.Contains(classNameSpace))
  260. {
  261. entitylist.Add(t);
  262. }
  263. }
  264. }
  265. }
  266. foreach (Type type in entitylist)
  267. {
  268. string dbSeedFilePath = dbSeedFileDirecPath + type.Name + ".json";
  269. if (File.Exists(dbSeedFilePath))
  270. {
  271. Type typeList = typeof(List<>);
  272. Type actualType = typeList.MakeGenericType(type);
  273. dynamic obj = Activator.CreateInstance(actualType);
  274. obj = JsonFileHelper.ReadjsonT<object>(dbSeedFilePath); // 加载数据
  275. //Db.Insertable(obj).ExecuteCommand(); // 未找到合适的无实体插入方法
  276. throw new Exception("批量插入请使用方法ImportDBSeed2!");
  277. }
  278. }
  279. }
  280. else
  281. {
  282. string dbSeedFilePath = dbSeedFileDirecPath + entity.GetType().Name + ".json";
  283. if (File.Exists(dbSeedFilePath))
  284. {
  285. T obj = JsonFileHelper.ReadjsonT<T>(dbSeedFilePath); // 加载数据
  286. Db.Insertable(obj);
  287. }
  288. }
  289. }
  290. /// <summary>
  291. /// 导入种子数据-批量
  292. /// ① DBSeed文件使用json文件保存;
  293. /// ② 一张表一个DBSeed文件;
  294. /// ③ 文件名字与表名保持一致;
  295. /// </summary>
  296. /// <param name="dbSeedFileDirec">DB种子数据所在的的文件夹(放在程序目录下)</param>
  297. /// <typeparam name="T"></typeparam>
  298. /// <param name="entity">指定Entity名;不指定时生成指定作用域中/默认作用域(一般指文件夹名)下所有Entity的表的数据</param>
  299. /// <param name="dllName">指定实体类的包名</param>
  300. /// <param name="classNameSpaces">指定实体类的包名</param>
  301. /// <exception cref="NotImplementedException"></exception>
  302. public void ImportDBSeed2(string dbSeedFileDirec)
  303. {
  304. var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
  305. string dbSeedFileDirecPath = path + dbSeedFileDirec + @"/";
  306. if (!Directory.Exists(dbSeedFileDirecPath))
  307. {
  308. throw new Exception("DB数据初始化失败!在程序目录下找不到DB种子数据文件夹!");
  309. }
  310. #region 设置DBSeed
  311. //ImportDBSeed2<SYS_USER>(dbSeedFileDirecPath);
  312. //ImportDBSeed2<SYS_USER_ROLE>(dbSeedFileDirecPath);
  313. #endregion 设置DBSeed
  314. }
  315. /// <summary>
  316. /// ImportDBSeed2-导入种子数据
  317. /// </summary>
  318. /// <typeparam name="T"></typeparam>
  319. /// <param name="dbSeedFileDirecPath">文件夹路径</param>
  320. private void ImportDBSeed2<T>(string dbSeedFileDirecPath) where T : class, new()
  321. {
  322. string dbSeedFilePath = dbSeedFileDirecPath + new T().GetType().Name + ".json";
  323. if (File.Exists(dbSeedFilePath))
  324. {
  325. var objs = JsonFileHelper.ReadjsonT<List<T>>(dbSeedFilePath); // 加载数据
  326. Db.Insertable<T>(objs).ExecuteCommand();
  327. }
  328. }
  329. /// <summary>
  330. /// 导出种子数据
  331. /// </summary>
  332. /// <typeparam name="T"></typeparam>
  333. /// <param name="dbSeedFileDirec">DB种子数据导出的文件夹(生成在程序目录下)</param>
  334. /// <param name="entity">指定Entity名;不指定时生成指定作用域中/默认作用域(一般指文件夹名)下所有Entity的表的数据</param>
  335. /// <param name="dllName">指定实体类的包名</param>
  336. /// <param name="classNameSpaces">指定实体类的包名</param>
  337. public void ExportDBSeed<T>(string dbSeedFileDirec, T entity = null, string dllName = "BOZHON.Repository.dll", string[] classNameSpaces = null) where T : class, new()
  338. {
  339. classNameSpaces = classNameSpaces == null ? new string[] { "Entity" } : classNameSpaces;
  340. var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
  341. string dbSeedFileDirecPath = path + dbSeedFileDirec + @"/";
  342. if (!Directory.Exists(dbSeedFileDirecPath))
  343. {
  344. Directory.CreateDirectory(dbSeedFileDirecPath); // 生成目录
  345. }
  346. if (entity is null)
  347. {
  348. List<Type> entitylist = new List<Type>();
  349. if (!string.IsNullOrWhiteSpace(dllName))
  350. {
  351. dllName = path + dllName;
  352. Assembly assembly = Assembly.LoadFrom(dllName);
  353. Type[] ts = assembly.GetTypes();
  354. foreach (string classNameSpace in classNameSpaces)
  355. {
  356. foreach (Type t in ts)
  357. {
  358. if (t.FullName.Contains(classNameSpace))
  359. {
  360. entitylist.Add(t);
  361. }
  362. }
  363. }
  364. }
  365. foreach (Type type in entitylist)
  366. {
  367. string dbSeedFilePath = dbSeedFileDirecPath + type.Name + ".json";
  368. var seedDatas = Db.Queryable(type.Name, type.Name).ToList();
  369. JsonFileHelper.WritejsonT(dbSeedFilePath, seedDatas);
  370. }
  371. }
  372. else
  373. {
  374. string dbSeedFilePath = dbSeedFileDirecPath + entity.GetType().Name + ".json";
  375. var seedDatas = Db.Queryable<T>().ToList();
  376. JsonFileHelper.WritejsonT(dbSeedFilePath, seedDatas);
  377. }
  378. }
  379. }
  380. }