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
{
///
/// 连接
///
public class PracticeContext
{
//private static readonly string _connectionString = ConfigurationManager.AppSettings["DefaultConnection"];
///
///
///
public SqlSugarClient Db;
///
/// 初始化
///
/// 连接字符串名称
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;
// // 记录执行的信息
//};
}
///
/// 初始化
///
/// 连接字符串名称
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;
// // 记录执行的信息
//};
}
///
/// 根据Entity(实体)生成数据库中的表
///
///
/// 指定Entity名;不指定时生成指定作用域中/默认作用域(一般指文件夹名)下所有Entity的表结构
/// 指定类的包名
/// 指定类的包名
public void CodeFirst(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 entitylist = new List();
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));
}
}
///
/// 导入种子数据
/// 注:批量不可用(指定Entity名时功能可用,通过“classNameSpaces”批量导入时功能不可用)
/// ① DBSeed文件使用json文件保存;
/// ② 一张表一个DBSeed文件;
/// ③ 文件名字与表名保持一致;
///
/// DB种子数据所在的的文件夹(放在程序目录下)
///
/// 指定Entity名;不指定时生成指定作用域中/默认作用域(一般指文件夹名)下所有Entity的表的数据
/// 指定实体类的包名
/// 指定实体类的包名
///
public void ImportDBSeed(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 entitylist = new List();
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