-
Notifications
You must be signed in to change notification settings - Fork 5
/
DbContextSetExpand.cs
834 lines (792 loc) · 32 KB
/
DbContextSetExpand.cs
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using Jc.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Collections;
using System.Reflection;
using System.Collections.Specialized;
using Jc.Data.Model;
using Jc.Data.Query;
using System.Threading.Tasks;
using System.Collections.Concurrent;
namespace Jc
{
/// <summary>
/// DbContext
/// DbContext数据操作访问
/// </summary>
public partial class DbContext
{
#region SetMethods
/// <summary>
/// 保存or更新数据对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dto">实体对象</param>
/// <param name="select">查询属性</param>
public int Set<T>(T dto,Expression<Func<T, object>> select = null) where T : class, new()
{
if (dto == null)
{
throw new Exception("操作对象不能为空.");
}
int rowCount = 0;
DtoMapping dtoDbMapping = DtoMappingHelper.GetDtoMapping<T>();
object pkValue = dtoDbMapping.PkMap.Pi.GetValue(dto);
if (CheckIsNullOrEmpty(pkValue, dtoDbMapping.PkMap.PropertyType))
{
rowCount = Add(dto, select);
}
else
{
rowCount = Update(dto, select);
}
return rowCount;
}
/// <summary>
/// 批量插入或批量更新记录,不能同时插入和更新数据
/// 以第一条数据主键属性值判断,插入或更新
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">实体对象</param>
/// <param name="select">查询属性</param>
/// <param name="useTransaction">使用事务操作 默认true</param>
/// <param name="progress">保存进度</param>
public int SetList<T>(List<T> list, Expression<Func<T, object>> select = null, bool useTransaction = true, IProgress<double> progress = null) where T : class, new()
{
if(list==null || list.Count<=0)
{
return 0;
}
int rowCount = 0;
DtoMapping dtoDbMapping = DtoMappingHelper.GetDtoMapping<T>();
object pkValue = dtoDbMapping.PkMap.Pi.GetValue(list[0]);
if (CheckIsNullOrEmpty(pkValue, dtoDbMapping.PkMap.PropertyType))
{
rowCount = AddList(list, select, useTransaction, progress);
}
else
{
rowCount = UpdateList(list, select, useTransaction, progress);
}
return rowCount;
}
/// <summary>
/// 批量保存数据
/// 批量操作数据为插入和更新操作的数据List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">实体对象</param>
/// <param name="select">查询属性</param>
/// <param name="useTransaction">使用事务操作 默认true</param>
/// <param name="progress">保存进度</param>
private int SetList_Bak<T>(List<T> list, Expression<Func<T, object>> select = null, bool useTransaction = true, IProgress<double> progress = null) where T : class, new()
{
if (list == null || list.Count <= 0)
{
return 0;
}
int rowCount = 0;
DtoMapping dtoDbMapping = DtoMappingHelper.GetDtoMapping<T>();
List<T> addList = new List<T>();
List<T> updateList = new List<T>();
#region 拆分新增或更新对象List
for (int i = 0; i < list.Count; i++)
{
object pkValue = dtoDbMapping.PkMap.Pi.GetValue(list[i]);
if (CheckIsNullOrEmpty(pkValue, dtoDbMapping.PkMap.PropertyType))
{
addList.Add(list[i]);
}
else
{
updateList.Add(list[i]);
}
}
#endregion
if (useTransaction)
{
if (addList.Count > 0 && updateList.Count > 0)
{
throw new Exception("插入和更新操作同时存在时,不能启用事务.");
}
}
if (addList.Count > 0)
{
rowCount += AddList(addList, select, useTransaction, progress);
}
if (updateList.Count > 0)
{
rowCount += UpdateList(updateList, select, useTransaction, progress);
}
return rowCount;
}
/// <summary>
/// 异步批量保存数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">实体对象 List</param>
/// <param name="select">查询属性</param>
/// <param name="useTransaction">使用事务操作 默认true</param>
/// <param name="progress">进度通知</param>
public async Task<int> SetListSync<T>(List<T> list, Expression<Func<T, object>> select = null, bool useTransaction = true, IProgress<double> progress = null) where T : class, new()
{
int rowCount = await Task.Run(() => { return SetList(list, select, useTransaction, progress); });
return rowCount;
}
/// <summary>
/// 保存数据对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dto">实体对象</param>
/// <param name="select">查询属性</param>
public int Add<T>(T dto, Expression<Func<T, object>> select = null) where T : class, new()
{
if (dto == null)
{
throw new Exception("待保存对象不能为空");
}
int rowCount = 0;
DtoMapping dtoDbMapping = DtoMappingHelper.GetDtoMapping<T>();
List<PiMap> piMapList = DtoMappingHelper.GetPiMapList<T>(select);
if (dtoDbMapping.TableAttr.AutoCreate)
{ //如果是自动建表
if (!CheckTableExists<T>())
{
CreateTable<T>();
}
}
object pkValue = dtoDbMapping.PkMap.Pi.GetValue(dto);
if (!dtoDbMapping.IsAutoIncrementPk)
{ //Guid Id
if (pkValue == null || (Guid)pkValue == Guid.Empty)
{ //生成Guid
dtoDbMapping.PkMap.Pi.SetValue(dto, Guid.NewGuid());
}
if (!piMapList.Contains(dtoDbMapping.PkMap))
{
piMapList.Insert(0, dtoDbMapping.PkMap);
}
}
using (DbCommand dbCommand = dbProvider.GetInsertDbCmd(dto, piMapList, this.GetSubTableArg<T>()))
{
try
{
SetDbConnection(dbCommand); // 添加记录
if ((dtoDbMapping.PkMap.PropertyType == typeof(int)
|| dtoDbMapping.PkMap.PropertyType == typeof(int?))
&& (pkValue == null || (int)pkValue == 0))
{
dbCommand.CommandText += ";" + dbProvider.GetAutoIdDbCommand().CommandText;
object valueObj = dbCommand.ExecuteScalar();
if (valueObj == null || valueObj == DBNull.Value)
{
throw new Exception("插入记录失败.");
}
dtoDbMapping.PkMap.Pi.SetValue(dto, Convert.ToInt32(valueObj));
}
else if ((dtoDbMapping.PkMap.PropertyType == typeof(long) ||
dtoDbMapping.PkMap.PropertyType == typeof(long?))
&& (pkValue == null || (long)pkValue == 0))
{
dbCommand.CommandText = $"{dbCommand.CommandText};{dbProvider.GetAutoIdDbCommand().CommandText}";
object valueObj = dbCommand.ExecuteScalar();
if (valueObj == null || valueObj == DBNull.Value)
{
throw new Exception("插入记录失败.");
}
dtoDbMapping.PkMap.Pi.SetValue(dto, Convert.ToInt64(valueObj));
}
else
{
rowCount = dbCommand.ExecuteNonQuery();
if (rowCount <= 0)
{
throw new Exception("插入记录失败.");
}
}
CloseDbConnection(dbCommand);
}
catch (Exception ex)
{
CloseDbConnection(dbCommand);
throw ex;
}
}
return rowCount;
}
/// <summary>
/// 批量添加数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">实体对象 List</param>
/// <param name="select">查询属性</param>
/// <param name="useTransaction">使用事务操作 默认true</param>
/// <param name="progress">进度通知</param>
public int AddList<T>(List<T> list, Expression<Func<T, object>> select = null,bool useTransaction = true, IProgress<double> progress = null) where T : class, new()
{
if (list == null || list.Count <= 0)
{
return 0;
}
int rowCount = 0;
DtoMapping dtoDbMapping = DtoMappingHelper.GetDtoMapping<T>();
List<PiMap> piMapList = DtoMappingHelper.GetPiMapList<T>(select);
if (!dtoDbMapping.IsAutoIncrementPk && !piMapList.Contains(dtoDbMapping.PkMap))
{
piMapList.Insert(0,dtoDbMapping.PkMap);
}
if (dtoDbMapping.TableAttr.AutoCreate)
{ //如果是自动建表
if (!CheckTableExists<T>())
{
CreateTable<T>();
}
}
//因为参数有2100的限制
int perOpAmount = 2000/ piMapList.Count; //每次添加Amount
if (useTransaction && !isTransaction)
{
#region Use Transaction
DbConnection dbConnection = GetDbConnection();
DbTransaction transaction = dbConnection.BeginTransaction();
int i = 0;
T curItem;
try
{
List<T> curOpList = new List<T>();
for (i = 0; i < list.Count; i++)
{
#region 设置Id
curItem = list[i];
object pkValue = dtoDbMapping.PkMap.Pi.GetValue(list[i]);
if (dtoDbMapping.PkMap.PropertyType == typeof(int) || dtoDbMapping.PkMap.PropertyType == typeof(int?))
{ //自增Id
}
else if (dtoDbMapping.PkMap.PropertyType == typeof(long) || dtoDbMapping.PkMap.PropertyType == typeof(long?))
{
}
else if (dtoDbMapping.PkMap.PropertyType == typeof(Guid) || dtoDbMapping.PkMap.PropertyType == typeof(Guid?))
{ //Guid Id
if (pkValue == null || (Guid)pkValue == Guid.Empty)
{ //生成Guid
dtoDbMapping.PkMap.Pi.SetValue(list[i], Guid.NewGuid());
}
}
#endregion
curOpList.Add(list[i]);
if ((i + 1) % perOpAmount == 0 || i == list.Count - 1)
{
using (DbCommand dbCommand = dbProvider.GetInsertDbCmd(curOpList, piMapList, this.GetSubTableArg<T>()))
{
dbCommand.Connection = dbConnection;
dbCommand.Transaction = transaction;
rowCount += dbCommand.ExecuteNonQuery();
}
curOpList.Clear();
if (progress != null)
{
progress.Report((i + 1) * 1.0 / list.Count);
}
}
}
transaction.Commit();
CloseDbConnection(dbConnection);
}
catch (Exception ex)
{
transaction.Rollback();
CloseDbConnection(dbConnection);
throw ex;
}
#endregion
}
else
{
#region Not Use Transaction
int i = 0;
T curItem;
List<T> curOpList = new List<T>();
for (i = 0; i < list.Count; i++)
{
#region 设置Id
curItem = list[i];
object pkValue = dtoDbMapping.PkMap.Pi.GetValue(list[i]);
if (dtoDbMapping.PkMap.PropertyType == typeof(Guid) || dtoDbMapping.PkMap.PropertyType == typeof(Guid?))
{ //Guid Id
if (pkValue == null || (Guid)pkValue == Guid.Empty)
{ //生成Guid
dtoDbMapping.PkMap.Pi.SetValue(list[i], Guid.NewGuid());
}
}
#endregion
curOpList.Add(list[i]);
if ((i + 1) % perOpAmount == 0 || i == list.Count - 1)
{
using (DbCommand dbCommand = dbProvider.GetInsertDbCmd(curOpList, piMapList, this.GetSubTableArg<T>()))
{
try
{
SetDbConnection(dbCommand);
rowCount += dbCommand.ExecuteNonQuery();
CloseDbConnection(dbCommand);
}
catch (Exception ex)
{
CloseDbConnection(dbCommand);
throw ex;
}
}
curOpList.Clear();
if (progress != null)
{
progress.Report((i + 1) * 1.0 / list.Count);
}
}
}
#endregion
}
return rowCount;
}
/// <summary>
/// 异步批量添加数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">实体对象 List</param>
/// <param name="select">查询属性</param>
/// <param name="useTransaction">使用事务操作 默认true</param>
/// <param name="progress">进度通知</param>
public async Task<int> AddListSync<T>(List<T> list, Expression<Func<T, object>> select = null, bool useTransaction = true, IProgress<double> progress = null) where T : class, new()
{
int rowCount = await Task.Run(() => { return AddList(list, select, useTransaction, progress); });
return rowCount;
}
/// <summary>
/// 更新数据对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dto">实体对象</param>
/// <param name="select">更新属性</param>
public int Update<T>(T dto,Expression<Func<T, object>> select = null) where T : class, new()
{
if (dto == null)
{
throw new Exception("待更新对象不能为空.");
}
int rowCount = 0;
DtoMapping dtoDbMapping = DtoMappingHelper.GetDtoMapping<T>();
List<PiMap> piMapList = DtoMappingHelper.GetPiMapList<T>(select);
using (DbCommand dbCommand = dbProvider.GetUpdateDbCmd(dto, piMapList, this.GetSubTableArg<T>()))
{
try
{
SetDbConnection(dbCommand); // 更新记录
rowCount = dbCommand.ExecuteNonQuery();
if (rowCount <= 0)
{
//throw new Exception("没有更新任何记录.");
}
CloseDbConnection(dbCommand);
}
catch (Exception ex)
{
CloseDbConnection(dbCommand);
throw ex;
}
}
return rowCount;
}
/// <summary>
/// 更新数据对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">实体对象</param>
/// <param name="select">更新属性</param>
/// <param name="useTransaction">使用事务操作 默认true</param>
/// <param name="progress">进度通知</param>
public int UpdateList<T>(List<T> list, Expression<Func<T, object>> select = null, bool useTransaction = true, IProgress<double> progress = null) where T : class, new()
{
if (list == null || list.Count <= 0)
{
return 0;
}
int rowCount = 0;
DtoMapping dtoDbMapping = DtoMappingHelper.GetDtoMapping<T>();
List<PiMap> piMapList = DtoMappingHelper.GetPiMapList<T>(select);
if (dtoDbMapping.IsAutoIncrementPk)
{ //自增列Id不允许更新
if (piMapList.Contains(dtoDbMapping.PkMap))
{
piMapList.Remove(dtoDbMapping.PkMap);
}
}
//因为参数有2100的限制 待更新字段 + 主键
int perOpAmount = 2000 / (piMapList.Count + 1); //每次更新Amount
if (useTransaction && !isTransaction)
{
#region Use Transaction
DbConnection dbConnection = GetDbConnection();
DbTransaction transaction = dbConnection.BeginTransaction();
try
{
List<T> curOpList = new List<T>();
for (int i = 0; i < list.Count; i++)
{
curOpList.Add(list[i]);
if ((i + 1) % perOpAmount == 0 || i == list.Count - 1)
{
using (DbCommand dbCommand = dbProvider.GetUpdateDbCmd(curOpList, piMapList, this.GetSubTableArg<T>()))
{
dbCommand.Connection = dbConnection;
dbCommand.Transaction = transaction;
rowCount += dbCommand.ExecuteNonQuery();
}
curOpList.Clear();
if (progress != null)
{
progress.Report((i + 1) * 1.0 / list.Count);
}
}
}
transaction.Commit();
CloseDbConnection(dbConnection);
}
catch (Exception ex)
{
transaction.Rollback();
CloseDbConnection(dbConnection);
throw ex;
}
#endregion
}
else
{
#region Not Use Transaction
List<T> curOpList = new List<T>();
for (int i = 0; i < list.Count; i++)
{
curOpList.Add(list[i]);
if ((i + 1) % perOpAmount == 0 || i == list.Count - 1)
{
using (DbCommand dbCommand = dbProvider.GetUpdateDbCmd(curOpList, piMapList, this.GetSubTableArg<T>()))
{
try
{
SetDbConnection(dbCommand);
rowCount += dbCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
CloseDbConnection(dbCommand);
throw ex;
}
}
curOpList.Clear();
if (progress != null)
{
progress.Report((i + 1) * 1.0 / list.Count);
}
}
}
#endregion
}
return rowCount;
}
/// <summary>
/// 异步批量更新数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">实体对象 List</param>
/// <param name="select">查询属性</param>
/// <param name="useTransaction">使用事务操作 默认true</param>
/// <param name="progress">进度通知</param>
public async Task<int> UpdateListSync<T>(List<T> list, Expression<Func<T, object>> select = null, bool useTransaction = true, IProgress<double> progress = null) where T : class, new()
{
int rowCount = await Task.Run(() => { return UpdateList(list, select, useTransaction, progress); });
return rowCount;
}
/// <summary>
/// 根据Id删除数据
/// </summary>
/// <param name="id"></param>
public int DeleteById<T>(object id) where T : class, new()
{
int rowCount = 0;
using (DbCommand dbCommand = dbProvider.GetDeleteByIdDbCmd<T>(id, this.GetSubTableArg<T>()))
{
try
{
SetDbConnection(dbCommand); // 删除记录
rowCount = dbCommand.ExecuteNonQuery();
if (rowCount <= 0)
{
//throw new Exception("没有删除任何记录.");
}
CloseDbConnection(dbCommand);
}
catch (Exception ex)
{
CloseDbConnection(dbCommand);
throw ex;
}
}
return rowCount;
}
/// <summary>
/// 删除对象
/// </summary>
/// <param name="dto">对象</param>
public int Delete<T>(T dto) where T : class, new()
{
if (dto == null)
{
throw new Exception("待删除对象不能为空");
}
int rowCount = 0;
using (DbCommand dbCommand = dbProvider.GetDeleteDbCmd<T>(dto, this.GetSubTableArg<T>()))
{
try
{
SetDbConnection(dbCommand); // 删除记录
rowCount = dbCommand.ExecuteNonQuery();
if (rowCount <= 0)
{
//throw new Exception("没有删除任何记录.");
}
CloseDbConnection(dbCommand);
}
catch (Exception ex)
{
CloseDbConnection(dbCommand);
throw ex;
}
}
return rowCount;
}
/// <summary>
/// 条件删除
/// </summary>
/// <param name="where">删除条件</param>
public int Delete<T>(Expression<Func<T, bool>> where) where T : class, new()
{
if (where == null)
{
throw new Exception("删除条件不能为空");
}
int rowCount = 0;
QueryFilter filter = QueryFilterHelper.GetFilter(where);
using (DbCommand dbCommand = dbProvider.GetDeleteDbCmd<T>(filter, this.GetSubTableArg<T>()))
{
try
{
SetDbConnection(dbCommand); // 删除记录
rowCount = dbCommand.ExecuteNonQuery();
if (rowCount <= 0)
{
//throw new Exception("没有删除任何记录.");
}
CloseDbConnection(dbCommand);
}
catch (Exception ex)
{
CloseDbConnection(dbCommand);
throw ex;
}
}
return rowCount;
}
/// <summary>
/// 检查表是否已存在
/// </summary>
/// <typeparam name="T">T对象</typeparam>
/// <returns></returns>
public bool CheckTableExists<T>() where T : class, new()
{
bool result = false;
string subTableArg = this.GetSubTableArg<T>();
DtoMapping dtoDbMapping = DtoMappingHelper.GetDtoMapping<T>();
string tableName = dtoDbMapping.GetTableName(subTableArg);
using (DbCommand dbCommand = dbProvider.GetCheckTableExistsDbCommand(tableName))
{
try
{
SetDbConnection(dbCommand);
using (DbDataReader dr = dbCommand.ExecuteReader())
{
result = dr.HasRows;
dr.Close();
}
CloseDbConnection(dbCommand);
}
catch (Exception ex)
{
CloseDbConnection(dbCommand);
throw ex;
}
}
return result;
}
/// <summary>
/// 新建表
/// </summary>
/// <typeparam name="T">需要为T各属性指定相应的FieldDbType,及长度等属性</typeparam>
/// <returns></returns>
public void CreateTable<T>() where T : class, new()
{
using (DbCommand dbCommand = dbProvider.GetCreateTableDbCommand<T>(this.GetSubTableArg<T>()))
{
try
{
SetDbConnection(dbCommand); // 创建表
dbCommand.ExecuteNonQuery();
CloseDbConnection(dbCommand);
}
catch (Exception ex)
{
CloseDbConnection(dbCommand);
throw ex;
}
}
}
/// <summary>
/// Obj IsNullOrEmpty
/// 默认严格模式下string.Empty,Guid.Empty,int 0,ICollection.Count 0 都会被作为false
/// </summary>
/// <param name="obj">对象</param>
/// <param name="objType">对象类型</param>
/// <param name="isStrict">严格模式</param>
/// <returns></returns>
private bool CheckIsNullOrEmpty(object obj,Type objType, bool isStrict = true)
{
bool result = false;
if (obj == null)
{
result = true;
}
else if (isStrict)
{
Type type = objType;
if (type == typeof(string))
{
if (string.IsNullOrEmpty(obj.ToString()))
{
result = true;
}
}
else if (type == typeof(Guid) || type == typeof(Guid?))
{
if (((Guid)obj) == Guid.Empty)
{
result = true;
}
}
else if (type == typeof(int) || type == typeof(int?))
{
if (((int)obj) == 0)
{
result = true;
}
}
else if (type == typeof(long) || type == typeof(long?))
{
if (((long)obj) == 0)
{
result = true;
}
}
else if (obj is ICollection)
{
ICollection collection = obj as ICollection;
if (collection.Count <= 0)
{
result = true;
}
}
}
return result;
}
/// <summary>
/// 使用BulkCopy插入数据
/// 目前仅支持MsSql(Sql Server)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">数据List</param>
/// <param name="batchSize">BatchSize</param>
/// <param name="timeout">BulkCopyTimeout</param>
/// <param name="useTransaction">使用事务</param>
/// <param name="progress">0,1 进度</param>
public void BulkCopy<T>(List<T> list, int batchSize, int timeout = 0, bool useTransaction = true, IProgress<float> progress = null)
{
if (list == null || list.Count <= 0)
{
return;
}
DtoMapping dtoDbMapping = DtoMappingHelper.GetDtoMapping<T>();
string tableName = dtoDbMapping.GetTableName();
DataTable dt = EntityToDataTable(list);
dbProvider.BulkCopy(tableName, dt, batchSize, timeout, useTransaction, progress);
}
/// <summary>
/// Convert List To DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
private DataTable EntityToDataTable<T>(List<T> list)
{
DataTable dt = new DataTable();
List<FieldModel> fields = GetTableFieldList<T>();
DtoMapping dtoDbMapping = DtoMappingHelper.GetDtoMapping<T>();
string tableName = dtoDbMapping.GetTableName();
List<PiMap> piMaps = DtoMappingHelper.GetPiMapList<T>();
List<PiMap> mappingPis = new List<PiMap>();
for (int i = 0; i < fields.Count; i++)
{
FieldModel field = fields[i];
PiMap piMap = piMaps.FirstOrDefault(a => a.FieldName.ToLower() == field.FieldName.ToLower());
if (piMap == null)
{
throw new Exception($"{dtoDbMapping.EntityType.FullName} 未定义与表 '{tableName}' 列名为 '{field.FieldName}' 映射的属性");
}
mappingPis.Add(piMap);
Type realType = piMap.PropertyType.GenericTypeArguments.Length > 0 ?
piMap.PropertyType.GenericTypeArguments[0] : piMap.PropertyType;
if (realType.IsEnum)
{
realType = typeof(int);
}
dt.Columns.Add(new DataColumn(field.FieldName, realType));
}
foreach (T dto in list)
{
DataRow dr = dt.NewRow();
for (int i = 0; i < mappingPis.Count; i++)
{
PiMap piMap = mappingPis[i];
object value = piMap.Pi.GetValue(dto);
if (piMap == dtoDbMapping.PkMap && !dtoDbMapping.IsAutoIncrementPk)
{ //是否需要生成Guid
if (value == null || (Guid)value == Guid.Empty)
{
value = Guid.NewGuid();
piMap.Pi.SetValue(dto, value);
}
}
if (piMap.IsEnum)
{
if (value != null)
value = (int)value;
}
dr[i] = value ?? DBNull.Value;
}
dt.Rows.Add(dr);
}
return dt;
}
#endregion
}
}