Repository.cs
11.1 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Infrastructure;
using Microsoft.EntityFrameworkCore;
using Z.EntityFramework.Plus;
namespace WebRepository
{
public class Repository<T> : IRepository<T> where T : SysEntity
{
private BaseDbContext _context;
public LoginInfo _loginInfo { get; set; }
public Repository(BaseDbContext context)
{
_context = context;
}
public bool IsExist(Expression<Func<T, bool>> exp)
{
return _context.Set<T>().Any(exp);
}
/// <summary>
/// 查找单个,且不被上下文所跟踪
/// </summary>
public T FindSingle(Expression<Func<T, bool>> exp)
{
return _context.Set<T>().AsNoTracking().FirstOrDefault(exp);
}
/// <summary>
/// 根据过滤条件,获取记录
/// </summary>
/// <param name="exp">The exp.</param>
public IQueryable<T> Find(Expression<Func<T, bool>> exp = null)
{
return Filter(exp);
}
/// <summary>
/// 得到分页记录
/// </summary>
/// <param name="pageindex">The pageindex.</param>
/// <param name="pagesize">The pagesize.</param>
/// <param name="orderby">排序,格式如:"Id"/"Id descending"</param>
/// <param name="exp">表达式</param>
public IQueryable<T> Find(int pageindex, int pagesize, string orderby = "", Expression<Func<T, bool>> exp = null)
{
if (pageindex < 1) pageindex = 1;
if (string.IsNullOrEmpty(orderby))
orderby = "Id descending";
return Filter(exp).OrderBy(orderby).Skip(pagesize * (pageindex - 1)).Take(pagesize);
}
/// <summary>
/// 根据过滤条件获取记录数
/// </summary>
public int GetCount(Expression<Func<T, bool>> exp = null)
{
return Filter(exp).Count();
}
public void Add(T entity)
{
entity.CreateBy = _loginInfo.Account;
entity.CreateTime = DateTime.Now;
_context.Set<T>().Add(entity);
Save();
}
/// <summary>
/// 批量添加
/// </summary>
/// <param name="entities">The entities.</param>
public void BatchAdd(T[] entities)
{
foreach (var entity in entities)
{
entity.CreateBy = _loginInfo.Account;
entity.CreateTime = DateTime.Now;
}
_context.Set<T>().AddRange(entities);
Save();
}
public void Update(T entity)
{
if (string.IsNullOrEmpty(entity.CreateBy))
{
T oldentity = FindSingle(u => u.Id == entity.Id);
entity.CreateBy = oldentity.CreateBy;
entity.CreateTime = oldentity.CreateTime;
}
entity.UpdateBy = _loginInfo.Account;
entity.UpdateTime = DateTime.Now;
var entry = this._context.Entry(entity);
entry.State = EntityState.Modified;
//如果数据没有发生变化
if (!this._context.ChangeTracker.HasChanges())
{
return;
}
Save();
}
public void UpdateByTracking(T entity)
{
if (string.IsNullOrEmpty(entity.CreateBy))
{
T oldentity = FindSingle(u => u.Id == entity.Id);
entity.CreateBy = oldentity.CreateBy;
entity.CreateTime = oldentity.CreateTime;
}
entity.UpdateBy = _loginInfo.Account;
entity.UpdateTime = DateTime.Now;
T entity_exist = _context.Set<T>().AsQueryable().Where(u => u.Id.Equals(entity.Id)).FirstOrDefault();
if (entity_exist != null)
{
foreach (var property in entity_exist.GetType().GetProperties())
{
var propertyValue = entity.GetType().GetProperty(property.Name).GetValue(entity, null);
if (propertyValue != null)
{
if (propertyValue.GetType().IsClass)
{
}
entity_exist.GetType().InvokeMember(property.Name, BindingFlags.SetProperty, null, entity_exist, new object[] { propertyValue });
}
}
foreach (var field in entity_exist.GetType().GetFields())
{
var fieldValue = entity.GetType().GetField(field.Name).GetValue(entity);
if (fieldValue != null)
{
entity_exist.GetType().InvokeMember(field.Name, BindingFlags.SetField, null, entity_exist, new object[] { fieldValue });
}
}
var entry = this._context.Entry(entity_exist);
entry.State = EntityState.Modified;
//如果数据没有发生变化
if (!this._context.ChangeTracker.HasChanges())
{
return;
}
}
else
{
var entry = this._context.Entry(entity);
entry.State = EntityState.Modified;
//如果数据没有发生变化
if (!this._context.ChangeTracker.HasChanges())
{
return;
}
}
Save();
}
/// <summary>
/// 实现按需要只更新部分更新
/// <para>如:Update(u =>u.Id==1,u =>new User{Name="ok"});</para>
/// </summary>
/// <param name="where">The where.</param>
/// <param name="entity">The entity.</param>
public void Update(Expression<Func<T, bool>> where, Expression<Func<T, T>> entity)
{
_context.Set<T>().Where(where).Update(entity);
Save();
}
public void Delete(T entity)
{
_context.Set<T>().Remove(entity);
Save();
}
public void DeleteByTracking(T entity)
{
T entity_exist = _context.Set<T>().AsQueryable().Where(u => u.Id.Equals(entity.Id)).FirstOrDefault();
if (entity_exist != null)
{
_context.Set<T>().Remove(entity_exist);
}
else
{
_context.Set<T>().Remove(entity);
}
Save();
}
public virtual void Delete(Expression<Func<T, bool>> exp)
{
System.Collections.Generic.List<T> entitys = _context.Set<T>().Where(exp).ToList();
foreach (var item in entitys)
{
Delete(item);
}
}
public void Save()
{
try
{
_context.SaveChanges();
}
catch (Exception ex)
{
string sMessage = ex.Message;
if (ex.InnerException != null)
{
sMessage = ex.InnerException.Message;
if (ex.InnerException.InnerException != null)
{
sMessage = ex.InnerException.InnerException.Message;
}
}
throw new Exception(sMessage);
}
}
public int ExecuteSql(string sql)
{
try
{
return _context.Database.ExecuteSqlRaw(sql);
}
catch (Exception ex)
{
throw new Exception(ex.Message.Replace("ROLLBACK TRANSACTION 请求没有对应的 BEGIN TRANSACTION。", "", StringComparison.CurrentCulture));
}
}
public TableData Load(PageReq pageRequest, T entity)
{
var result = new TableData();
var data = Find(EntityToExpression<T>.GetExpressions(entity));
GetData(data, result, pageRequest);
result.count = data.Count();
return result;
}
public TableData ExportData(T entity)
{
var result = new TableData();
var data = Find(EntityToExpression<T>.GetExpressions(entity));
GetData(data, result);
result.count = data.Count();
return result;
}
public void GetData(IQueryable<T> data, TableData result, PageReq pageRequest = null)
{
int skipPage = 0;
int takeCount = data.Count();
string odby = "";
string sfield = "";
if (data.Count() == 0) return;
if (pageRequest != null)
{
skipPage = (pageRequest.page - 1) * pageRequest.limit;
takeCount = pageRequest.limit;
odby = pageRequest.order;
sfield = pageRequest.field;
}
if (string.IsNullOrEmpty(sfield))
{
odby = "asc";
sfield = "Id";
}
bool isAsc = odby == "desc" ? false : true;
List<T> data1;
if (string.IsNullOrEmpty(sfield))
data1 = data.Skip(skipPage).Take(takeCount).ToList();
else
data1 = data.OrderBy(sfield, isAsc).Skip(skipPage).Take(takeCount).ToList();
result.data = data1;
}
private IQueryable<T> Filter(Expression<Func<T, bool>> exp)
{
var dbSet = _context.Set<T>().AsNoTracking().AsQueryable();
if (exp != null)
dbSet = dbSet.Where(exp);
return dbSet;
}
/// <summary>
/// 获取任务号
/// </summary>
/// <param name="TaskType">TaskType.</param>
/// <param name="SeqLength">长度.</param>
public string GetTaskNo(string TaskType, int SeqLength = 4)
{
string Value = "1";
SysCount sysCount = _context.Set<SysCount>().AsNoTracking().FirstOrDefault(u => u.Type == TaskType);
if (sysCount == null)
{
Value = TaskType + DateTime.Now.ToString("yyyyMMdd") + Value.PadLeft(SeqLength, '0');
sysCount = new SysCount { Type = TaskType, Value = Value };
_context.Set<SysCount>().Add(sysCount);
Save();
}
else
{
string Date = sysCount.Value.Substring(TaskType.Length, 8);
if (Date == DateTime.Now.ToString("yyyyMMdd"))
{
Value = Date+(int.Parse(sysCount.Value.Substring(sysCount.Value.Length-4, 4)) + 1).ToString().PadLeft(SeqLength, '0');
}
else
{
Value = DateTime.Now.ToString("yyyyMMdd") + Value.PadLeft(SeqLength, '0');
}
Value = TaskType + Value;
_context.Set<SysCount>().Where(u => u.Type == TaskType).Update(u => new SysCount { Value = Value });
Save();
}
return Value;
}
}
}