using MES.Service.util;
|
using SqlSugar;
|
|
namespace MES.Service.DB;
|
|
/// <summary>
|
/// 数据仓储工厂
|
/// </summary>
|
/// <typeparam name="T"></typeparam>
|
public class DbContext<T> where T : class, new()
|
{
|
//DbContext<MesQaItemXj02> mesQaItemXj02Context = new DbContext<MesQaItemXj02>();
|
//mesQaItemXj02Context.Db.Queryable<MesQaItemXj02>().ToList();
|
|
private static readonly string connectionString =
|
AppsettingsUtility.Settings.DataBaseConn; // 这里替换成你的实际连接字符串;
|
|
/// <summary>
|
/// 注意:不能写成静态的 //用来处理事务多表查询和复杂的操作
|
/// </summary>
|
public SqlSugarClient Db;
|
|
/// <summary>
|
/// 入口
|
/// </summary>
|
public DbContext()
|
{
|
Db = new SqlSugarClient(new ConnectionConfig
|
{
|
ConnectionString = connectionString,
|
DbType = DbType.SqlServer,
|
InitKeyType = InitKeyType.Attribute, //从特性读取主键和自增列信息
|
IsAutoCloseConnection = true //开启自动释放模式和EF原理一样我就不多解释了
|
});
|
|
//调式代码 用来打印SQL
|
Db.Aop.OnLogExecuting = (sql, pars) =>
|
{
|
Console.WriteLine(sql + "\r\n" +
|
Db.Utilities.SerializeObject(
|
pars.ToDictionary(it => it.ParameterName,
|
it => it.Value)));
|
// LogHelper.LogWrite(sql + "\r\n" +Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
|
};
|
}
|
|
/// <summary>
|
/// 用来处理T表的常用操作
|
/// </summary>
|
public SimpleClient<T> CurrentDb => new(Db);
|
|
/// <summary>
|
/// 获取所有
|
/// </summary>
|
/// <returns></returns>
|
public virtual List<T> GetList()
|
{
|
return CurrentDb.GetList();
|
}
|
|
/// <summary>
|
/// 添加
|
/// </summary>
|
/// <param name="obj"></param>
|
/// <returns></returns>
|
public virtual bool Add(T obj)
|
{
|
return CurrentDb.Insert(obj);
|
}
|
|
/// <summary>
|
/// 根据主键删除
|
/// </summary>
|
/// <param name="id"></param>
|
/// <returns></returns>
|
public virtual bool Delete(dynamic id)
|
{
|
return CurrentDb.Delete(id);
|
}
|
|
/// <summary>
|
/// 更新
|
/// </summary>
|
/// <param name="obj"></param>
|
/// <returns></returns>
|
public virtual bool Update(T obj)
|
{
|
return CurrentDb.Update(obj);
|
}
|
}
|