DALHelper.cs
3.94 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
using FreeSql.Aop;
using HaHRCS.Rcs.Model.Entities;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace HaHRCS.Rcs.Dal {
public class DALHelper
{
/// <summary>
/// hack:正式使用请删除自动同步
/// </summary>
private static IFreeSql fsql;
private static readonly object lockObj = new object();
public static string Constr { get; set; }
/// <summary>
/// 获取freesql实例
/// </summary>
/// <returns></returns>
public static IFreeSql GetFreeSql()
{
if (fsql == null)
{
lock (lockObj)
{
if (fsql == null)
{
// fsql = new FreeSql.FreeSqlBuilder()
// .UseConnectionString(FreeSql.DataType.SqlServer, Constr)
//.UseAutoSyncStructure(true) //自动同步实体结构到数据库
//.Build(); //请务必定义成 Singleton 单例模式
#region SqlServer
fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.PostgreSQL, Constr)
// .UseAutoSyncStructure(true) //自动同步实体结构到数据库
.Build(); //请务必定义成 Singleton 单例模式
fsql.Aop.AuditValue += Aop_AuditValue;
fsql.Aop.CurdAfter += Aop_CurdAfter;
#endregion
}
}
}
return fsql;
}
/// <summary>
/// 记录超时Sql
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void Aop_CurdAfter(object sender, CurdAfterEventArgs e)
{
if (e.ElapsedMilliseconds > 2000)
{
Console.WriteLine($"SQL语句耗时过长:{e.ElapsedMilliseconds} -- {e.Sql}"); }
}
/// <summary>
/// 插入更新时,自动赋值created和updated
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void Aop_AuditValue(object sender, AuditValueEventArgs e)
{
if (e.AuditValueType == AuditValueType.Insert)
{
if (e.Property.Name == "Created")
{
e.Value = DateTime.Now;
}
}
if (e.AuditValueType == AuditValueType.Update)
{
if (e.Property.Name == "Updated")
{
e.Value = DateTime.Now;
}
}
if (e.AuditValueType == AuditValueType.InsertOrUpdate)
{
if (e.Property.Name == "Created" && e.Value == null)
{
e.Value = DateTime.Now;
}
if (e.Property.Name == "Updated")
{
e.Value = DateTime.Now;
}
}
}
/// <summary>
/// 同步表结构
/// </summary>
public static void SyncTable()
{
GetFreeSql().CodeFirst.SyncStructure(GetTypesByNameSpace());
}
public static Type[] GetTypesByNameSpace()
{
List<Type> tableAssembies = new List<Type>();
List<string> entitiesFullName = new List<string>()
{
"HHECS.Model.Entities"
};
foreach (Type type in Assembly.GetAssembly(typeof(BaseEntity<>)).GetExportedTypes())
foreach (var fullname in entitiesFullName)
if (type.FullName.StartsWith(fullname) && type.IsClass && type.IsAbstract == false)
tableAssembies.Add(type);
return tableAssembies.ToArray();
}
}
}