-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDbRepository.cs
More file actions
666 lines (576 loc) · 20.6 KB
/
Copy pathDbRepository.cs
File metadata and controls
666 lines (576 loc) · 20.6 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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
using Common;
using Common.DB;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Repository
{
/// <summary>
/// 描述:数据库仓储基类类
/// </summary>
public class DbRepository : IRepository
{
#region 构造函数
/// <summary>
/// 构造函数
/// </summary>
/// <param name="param">构造参数,可以为数据库连接字符串或者DbContext</param>
/// <param name="dbType">数据库类型</param>
public DbRepository(Object param, DatabaseType dbType, string entityNamespace)
{
BuildParam = param;
_dbType = dbType;
_entityNamespace = entityNamespace;
Handle_BuildDbContext = new Func<DbContext>(() =>
{
return DbFactory.GetDbContext(BuildParam, _dbType, _entityNamespace);
});
_db = Handle_BuildDbContext?.Invoke();
_connectionString = _db.Database.Connection.ConnectionString;
IsDisposed = false;
}
#endregion
#region 拥有成员
/// <summary>
/// 连接字符串
/// </summary>
protected string _connectionString { get; }
/// <summary>
/// 数据库类型
/// </summary>
private DatabaseType _dbType { get; set; }
/// <summary>
/// 连接上下文DbContext
/// </summary>
private DbContext _db { get; set; }
/// <summary>
/// 建造DbConText所需参数
/// </summary>
private Object BuildParam { get; set; }
/// <summary>
/// 实体命名空间
/// </summary>
private string _entityNamespace { get; set; }
/// <summary>
/// 标记DbContext是否已经释放
/// </summary>
protected bool IsDisposed { get; set; }
/// <summary>
/// 判断是否开始事物
/// </summary>
protected DbContextTransaction Transaction { get; set; }
protected DbContext Db
{
get
{
if (IsDisposed)
{
_db = Handle_BuildDbContext?.Invoke();
IsDisposed = false;
}
return _db;
}
set
{
_db = value;
}
}
protected static PropertyInfo GetKeyProperty<T>()
{
return GetKeyPropertys<T>().FirstOrDefault();
}
protected static List<PropertyInfo> GetKeyPropertys<T>()
{
var properties = typeof(T)
.GetProperties()
.Where(x => x.GetCustomAttributes(true).Select(o => o.GetType().FullName).Contains(typeof(KeyAttribute).FullName))
.ToList();
return properties;
}
protected static string GetDbTableName<T>()
{
string tableName = string.Empty;
var tableAttribute = typeof(T).GetCustomAttribute<TableAttribute>();
if (tableAttribute != null)
tableName = tableAttribute.Name;
else
tableName = typeof(T).Name;
return tableName;
}
protected static ObjectQuery<T> GetObjectQueryFromDbQueryable<T>(IQueryable<T> query)
{
var internalQueryField = query.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Where(f => f.Name.Equals("_internalQuery")).FirstOrDefault();
var internalQuery = internalQueryField.GetValue(query);
var objectQueryField = internalQuery.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Where(f => f.Name.Equals("_objectQuery")).FirstOrDefault();
return objectQueryField.GetValue(internalQuery) as ObjectQuery<T>;
}
private void CheckEntityState<T>(T entity) where T : class
{
if (Db.Entry(entity).State == EntityState.Detached)
{
var objectContext = ((IObjectContextAdapter)Db).ObjectContext;
var entitySet = objectContext.CreateObjectSet<T>();
var entityKey = objectContext.CreateEntityKey(entitySet.EntitySet.Name, entity);
object foundSet;
bool exists = objectContext.TryGetObjectByKey(entityKey, out foundSet);
if (exists)
{
objectContext.Detach(foundSet); //从上下文中移除
}
}
}
#endregion
#region 事件处理
Func<DbContext> Handle_BuildDbContext { get; set; }
#endregion
#region 事物相关
/// <summary>
/// 是否开启事务,单库事务
/// </summary>
protected bool _openedTransaction { get; set; } = false;
/// <summary>
/// 需要执行的Sql事务
/// </summary>
protected Action _sqlTransaction { get; set; }
/// <summary>
/// 提交到数据库
/// </summary>
protected void Commit()
{
//若未开启事物则直接提交到数据库
if (!_openedTransaction)
{
Db.SaveChanges();
Db.Dispose();
IsDisposed = true;
}
}
/// <summary>
/// 释放数据,初始化状态
/// </summary>
protected void Dispose()
{
Transaction?.Dispose();
Db?.Dispose();
IsDisposed = true;
_openedTransaction = false;
_sqlTransaction = null;
}
/// <summary>
/// 开始单库事物
/// 注意:若要使用跨库事务,请使用DistributedTransaction
/// </summary>
public void BeginTransaction()
{
Transaction = Db.Database.BeginTransaction();
_openedTransaction = true;
}
/// <summary>
/// 结束事物提交
/// </summary>
public bool EndTransaction()
{
bool isOK = true;
try
{
_sqlTransaction?.Invoke();
Db.SaveChanges();
Transaction.Commit();
}
catch
{
Transaction.Rollback();
isOK = false;
}
finally
{
Dispose();
}
return isOK;
}
#endregion
#region 数据库连接相关方法
/// <summary>
/// 获取DbContext
/// </summary>
/// <returns></returns>
public DbContext GetDbContext()
{
return Db;
}
public Action<string> HandleSqlLog
{
set
{
Db.Database.Log = value;
}
}
#endregion
#region 增加数据
/// <summary>
/// 插入数据
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entity">实体</param>
public void Insert<T>(T entity) where T : class, new()
{
Db.Entry(entity).State = EntityState.Added;
Commit();
}
/// <summary>
/// 插入数据列表
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entities">实体列表</param>
public void Insert<T>(List<T> entities) where T : class, new()
{
Db.Set<T>().AddRange(entities);
Commit();
}
/// <summary>
/// 使用Bulk批量插入数据(适合大数据量,速度非常快)
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entities">数据</param>
public virtual void BulkInsert<T>(List<T> entities) where T : class, new()
{
}
#endregion
#region 删除数据
/// <summary>
/// 删除表中所有数据
/// </summary>
/// <typeparam name="T">实体</typeparam>
public virtual void DeleteAll<T>() where T : class, new()
{
TableAttribute tableAttribute = typeof(T).GetCustomAttributes(typeof(TableAttribute), true).FirstOrDefault() as TableAttribute;
string tableName = tableAttribute.Name;
string sql = $"DELETE {tableName}";
ExecuteSql(sql);
}
/// <summary>
/// 删除一条数据
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="key">主键值</param>
public void Delete<T>(string key) where T : class, new()
{
T newData = new T();
var theProperty = GetKeyProperty<T>();
if (theProperty == null)
throw new Exception("该实体没有主键标识!请使用[Key]标识主键!");
var value = Convert.ChangeType(key, theProperty.PropertyType);
theProperty.SetValue(newData, value);
Delete(newData);
}
/// <summary>
/// 删除多条数据
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="keys">主键列表</param>
public void Delete<T>(List<string> keys) where T : class, new()
{
var theProperty = GetKeyProperty<T>();
if (theProperty == null)
throw new Exception("该实体没有主键标识!请使用[Key]标识主键!");
List<T> deleteList = new List<T>();
keys.ForEach(aKey =>
{
T newData = new T();
var value = Convert.ChangeType(aKey, theProperty.PropertyType);
theProperty.SetValue(newData, value);
deleteList.Add(newData);
});
Delete(deleteList);
}
/// <summary>
/// 删除一条数据
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entity">实体对象</param>
public void Delete<T>(T entity) where T : class, new()
{
CheckEntityState(entity);
Db.Set<T>().Attach(entity);
Db.Set<T>().Remove(entity);
Commit();
}
/// <summary>
/// 删除多条数据
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entities">数据列表</param>
public void Delete<T>(List<T> entities) where T : class, new()
{
foreach (var entity in entities)
{
CheckEntityState(entity);
Db.Set<T>().Attach(entity);
Db.Set<T>().Remove(entity);
}
Commit();
}
/// <summary>
/// 通过条件删除数据
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="condition">条件</param>
public void Delete<T>(Expression<Func<T, bool>> condition) where T : class, new()
{
var deleteList = GetIQueryable<T>().Where(condition).ToList();
Delete(deleteList);
}
/// <summary>
/// 通过条件删除数据
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="condition">条件</param>
public virtual void Delete_Sql<T>(Expression<Func<T, bool>> condition) where T : class, new()
{
var objectQuery = GetObjectQueryFromDbQueryable(GetIQueryable<T>().Where(condition));
string querySTr = objectQuery.ToTraceString();
string parttern = "^SELECT.*?FROM.*?AS(.*?)WHERE.*?$";
var match = Regex.Match(querySTr, parttern, RegexOptions.Singleline);
string extent1 = match.Groups[1].ToString();
parttern = "^SELECT.*?(FROM.*?AS.*?WHERE.*?$)";
match = Regex.Match(querySTr, parttern, RegexOptions.Singleline);
string fromSql = match.Groups[1].ToString();
string deleteSql = $"DELETE {extent1} {fromSql}";
List<DbParameter> dbParamters = new List<DbParameter>();
objectQuery.Parameters.ToList().ForEach(aParamter =>
{
var parameter = DbProviderFactoryHelper.GetDbParameter(_dbType);
parameter.ParameterName = aParamter.Name;
parameter.Value = aParamter.Value ?? DBNull.Value;
dbParamters.Add(parameter);
});
ExecuteSql(deleteSql, dbParamters);
}
#endregion
#region 更新数据
/// <summary>
/// 默认更新一个实体,所有字段
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
public void Update<T>(T entity) where T : class, new()
{
CheckEntityState(entity);
Db.Entry(entity).State = EntityState.Modified;
Commit();
}
/// <summary>
/// 默认更新实体列表,所有字段
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entities"></param>
public void Update<T>(List<T> entities) where T : class, new()
{
entities.ForEach(aEntity =>
{
CheckEntityState(aEntity);
Db.Entry(aEntity).State = EntityState.Modified;
});
Commit();
}
/// <summary>
/// 更新一条数据,某些属性
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entity">实体对象</param>
/// <param name="properties">需要更新的字段</param>
public void UpdateAny<T>(T entity, List<string> properties) where T : class, new()
{
CheckEntityState(entity);
Db.Set<T>().Attach(entity);
properties.ForEach(aProperty =>
{
Db.Entry(entity).Property(aProperty).IsModified = true;
});
Commit();
}
/// <summary>
/// 更新多条数据,某些属性
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entities">数据列表</param>
/// <param name="properties">需要更新的字段</param>
public void UpdateAny<T>(List<T> entities, List<string> properties) where T : class, new()
{
entities.ForEach(aEntity =>
{
CheckEntityState(aEntity);
Db.Set<T>().Attach(aEntity);
properties.ForEach(aProperty =>
{
Db.Entry(aEntity).Property(aProperty).IsModified = true;
});
});
Commit();
}
/// <summary>
/// 指定条件更新
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="whereExpre">筛选表达式</param>
/// <param name="set">更改属性回调</param>
public void UpdateWhere<T>(Expression<Func<T, bool>> whereExpre, Action<T> set) where T : class, new()
{
var list = GetIQueryable<T>().Where(whereExpre).ToList();
list.ForEach(aData => set(aData));
Update(list);
}
#endregion
#region 查询数据
/// <summary>
/// 获取实体
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="keyValue">主键</param>
/// <returns></returns>
public T GetEntity<T>(params object[] keyValue) where T : class, new()
{
return Db.Set<T>().Find(keyValue);
}
/// <summary>
/// 获取表的所有数据,当数据量很大时不要使用!
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <returns></returns>
public List<T> GetList<T>() where T : class, new()
{
return GetIQueryable<T>().ToList();
}
/// <summary>
/// 获取实体对应的表,延迟加载,主要用于支持Linq查询操作
/// 注意:无缓存
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <returns></returns>
public IQueryable<T> GetIQueryable<T>() where T : class, new()
{
return GetIQueryable(typeof(T)) as IQueryable<T>;
}
public IQueryable GetIQueryable(Type type)
{
if (BaseDbContext.NeedReloadDb(type))
Db = Handle_BuildDbContext?.Invoke();
return Db.Set(type).AsNoTracking();
}
/// <summary>
/// 通过Sql语句获取DataTable
/// </summary>
/// <param name="sql">Sql语句</param>
/// <returns></returns>
public DataTable GetDataTableWithSql(string sql)
{
return GetDataTableWithSql(sql, null);
}
/// <summary>
/// 通过Sql参数查询返回DataTable
/// </summary>
/// <param name="sql">Sql语句</param>
/// <param name="parameters">查询参数</param>
/// <returns></returns>
public DataTable GetDataTableWithSql(string sql, List<DbParameter> parameters)
{
DbProviderFactory dbProviderFactory = DbProviderFactories.GetFactory(Db.Database.Connection);
using (DbConnection conn = dbProviderFactory.CreateConnection())
{
conn.ConnectionString = _connectionString;
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
using (DbCommand cmd = conn.CreateCommand())
{
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.CommandTimeout = 5 * 60;
if (parameters != null && parameters?.Count > 0)
cmd.Parameters.AddRange(parameters.ToArray());
DbDataAdapter adapter = dbProviderFactory.CreateDataAdapter();
adapter.SelectCommand = cmd;
DataSet table = new DataSet();
adapter.Fill(table);
cmd.Parameters.Clear();
return table.Tables[0];
}
}
}
/// <summary>
/// 通过sql返回List
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="sqlStr">sql语句</param>
/// <returns></returns>
public List<T> GetListBySql<T>(string sqlStr) where T : class, new()
{
return Db.Database.SqlQuery<T>(sqlStr).ToList();
}
/// <summary>
/// 通过sql返回list
/// </summary>
/// <typeparam name="T">实体类</typeparam>
/// <param name="sqlStr">sql语句</param>
/// <param name="parameters">参数</param>
/// <returns></returns>
public List<T> GetListBySql<T>(string sqlStr, List<DbParameter> parameters) where T : class, new()
{
return Db.Database.SqlQuery<T>(sqlStr, parameters.ToArray()).ToList();
}
#endregion
#region 执行Sql语句
/// <summary>
/// 执行Sql语句
/// </summary>
/// <param name="sql">Sql语句</param>
public void ExecuteSql(string sql)
{
if (!_openedTransaction)
{
Db.Database.ExecuteSqlCommand(sql);
Dispose();
}
else
{
_sqlTransaction += new Action(() =>
{
Db.Database.ExecuteSqlCommand(sql);
});
}
}
/// <summary>
/// 通过参数执行Sql语句
/// </summary>
/// <param name="sql">Sql语句</param>
public void ExecuteSql(string sql, List<DbParameter> parameters)
{
if (!_openedTransaction)
{
Db.Database.ExecuteSqlCommand(sql, parameters.ToArray());
Dispose();
}
else
{
_sqlTransaction += new Action(() =>
{
Db.Database.ExecuteSqlCommand(sql, parameters.ToArray());
});
}
}
#endregion
}
}