zyf
2024-08-20 54cefea3fe69bf1d42c6114b68c9a2024c411c6f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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);
    }
}