forked from yuzd/AntMgr
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDbContext.cs
More file actions
97 lines (92 loc) · 3.17 KB
/
Copy pathDbContext.cs
File metadata and controls
97 lines (92 loc) · 3.17 KB
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
91
92
93
94
95
96
97
using AntData.ORM.Data;
using System;
using System.Diagnostics;
using System.Linq;
using Configuration;
using Infrastructure.Logging;
using Infrastructure.Web;
namespace DbModel
{
public class DbContext
{
/// <summary>
/// 后台系统采用的是什么数据库
/// </summary>
private static readonly string dbType;
private static readonly string dbMappingName;
static DbContext()
{
try
{
//读取当前采用的是什么数据库
dbMappingName = ConfigHelper.GetConfig<string>("AntDbType");
if (string.IsNullOrEmpty(dbMappingName))
{
throw new ArgumentException("AntDbType");
}
var dbProvider = AntData.ORM.Common.Configuration.DBSettings.DatabaseSettings.FirstOrDefault(r => r.Name.Equals(dbMappingName));
dbType = dbProvider?.Provider;
}
catch (Exception)
{
dbType = "mysql";
}
}
public static DbContext<AntEntity> DB
{
get
{
DbContext<AntEntity> db;
if (dbType.ToLower().Contains("mysql"))
{
db = new MysqlDbContext<AntEntity>(dbMappingName);
}
else
{
db = new SqlServerlDbContext<AntEntity>(dbMappingName);
}
#if DEBUG
db.IsEnableLogTrace = true;
db.OnLogTrace = OnCustomerTraceConnection;
#endif
return db;
}
}
/// <summary>
/// 记录sql
/// </summary>
/// <param name="customerTraceInfo"></param>
private static void OnCustomerTraceConnection(CustomerTraceInfo customerTraceInfo)
{
try
{
string sql = Environment.NewLine + "#####################################################" + Environment.NewLine + customerTraceInfo.SqlText;
try
{
sql = customerTraceInfo.CustomerParams.Aggregate(customerTraceInfo.SqlText,
(current, item) => current.Replace(item.Key, item.Value.Value.ToString()));
}
catch (Exception)
{
//ignore
}
sql += Environment.NewLine;
foreach (var detail in customerTraceInfo.RunTimeList)
{
var sencond = (int)detail.Duration.TotalSeconds;
var time = sencond + "秒";
if (sencond < 1)
{
time = detail.Duration.TotalMilliseconds + "豪秒";
}
sql += $"Server:{detail.Server},DB名称:{detail.DbName}, 执行时间:{time}" + Environment.NewLine + "#####################################################" + Environment.NewLine;
LogHelper.Info("SQL", sql);
}
}
catch (Exception)
{
//ignore
}
}
}
}