222
schangxiang@126.com
2024-11-27 19718e4a5dc6312173d4f44e630f50df2ee4f5b7
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
using Admin.NET.Core.Service;
using Admin.NET.Application.Entity;
using Microsoft.AspNetCore.Http;
using Furion.DatabaseAccessor;
using Yitter.IdGenerator;
 
namespace Admin.NET.Application.Service.CodeExamples;
/// <summary>
/// 代码示例服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.CodeExamplesGroupName, Order = 100)]
public class CodeExamplesService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<TestStudent> _rep;
    private readonly SqlSugarRepository<TestTeacher> _repTeacher;
    private readonly SqlSugarRepository<v_students> _rep_v_students;
    private readonly IUnitOfWork _unitOfWork;
    //private readonly SqlSugarUnitOfWork sugarUnitOfWork;
    public CodeExamplesService(SqlSugarRepository<TestStudent> rep, IUnitOfWork unitOfWork, SqlSugarRepository<TestTeacher> repTeacher, SqlSugarRepository<v_students> rep_v_students)
    {
        _rep = rep;
        _unitOfWork = unitOfWork;
        _repTeacher = repTeacher;
        _rep_v_students = rep_v_students;
    }
 
    /// <summary>
    /// 分页查询测试学生视图
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "PageStudentView")]
    [Description("CodeExamples/PageStudentView")]
    public async Task<SqlSugarPagedList<VTestStudentOutput>> PageStudentView(TestStudentInput input)
    {
        var query = _rep_v_students.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), u =>
                u.Name.Contains(input.SearchKey.Trim())
                || u.AliName.Contains(input.SearchKey.Trim())
            )
            .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.AliName), u => u.AliName.Contains(input.AliName.Trim()))
            .WhereIF(input.Age > 0, u => u.Age == input.Age)
            .WhereIF(input.NianJi > 0, u => u.NianJi == input.NianJi)
            .WhereIF(input.TeacherId > 0, u => u.TeacherId == input.TeacherId)
            .WhereIF(input.RectorId > 0, u => u.RectorId == input.RectorId)
            .WhereIF(input.IsInSchool.HasValue, u => u.IsInSchool == input.IsInSchool)
            .WhereIF(input.IsWDR.HasValue, u => u.IsWDR == input.IsWDR)
            .WhereIF(input.Gender.HasValue, u => u.Gender == input.Gender)
            .WhereIF(input.OtherGender.HasValue, u => u.OtherGender == input.OtherGender)
            .Select<VTestStudentOutput>();
        if (input.BrithDateRange != null && input.BrithDateRange.Count > 0)
        {
            DateTime? start = input.BrithDateRange[0].Value.AddDays(-1);
            query = query.WhereIF(start.HasValue, u => u.BrithDate > start);
            if (input.BrithDateRange.Count > 1 && input.BrithDateRange[1].HasValue)
            {
                var end = input.BrithDateRange[1].Value.AddDays(1);
                query = query.Where(u => u.BrithDate < end);
            }
        }
        if (input.InSchoolDateRange != null && input.InSchoolDateRange.Count > 0)
        {
            DateTime? start = input.InSchoolDateRange[0].Value.AddDays(-1);
            query = query.WhereIF(start.HasValue, u => u.InSchoolDate > start);
            if (input.InSchoolDateRange.Count > 1 && input.InSchoolDateRange[1].HasValue)
            {
                var end = input.InSchoolDateRange[1].Value.AddDays(1);
                query = query.Where(u => u.InSchoolDate < end);
            }
        }
        return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }
 
 
    /// <summary>
    /// 数据跟踪
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "GenZong")]
    [Description("CodeExamples/GenZong")]
    public async Task<TestStudent> GenZong()
    {
        //结论:sqlsugar没有ef跟踪的概念。
        var list = await _rep.AsQueryable().ToListAsync();
        if (list != null && list.Count > 0)
        {
            var first = list.First();
            first.Name = "我要改变值了";
 
 
            var aaa = await _rep.GetFirstAsync(u => u.Id == first.Id);
            //结果:aaa.Name还是数据库的值,不是新改的值,即 first和aaa不是一个对象
            var zz = "";
        }
        return null;
    }
 
    /// <summary>
    /// 正常---无事务 【无事务控制,不推荐】
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "NoTransDemo1")]
    [Description("CodeExamples/NoTransDemo1")]
    public async Task<long> NoTransDemo1()
    {
        await Commomn("", "正常---无事务");
 
        return 1;
    }
 
 
    /// <summary>
    /// 正常---特性事务    【正确写法】【正确】
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "NormalTransDemo1")]
    [Description("CodeExamples/NormalTransDemo1")]
    [UnitOfWork]
    public async Task<long> NormalTransDemo1()
    {
        await Commomn("", "正常---特性事务");
 
        return 1;
    }
 
    /// <summary>
    /// 正常---手写事务    【正确写法】【正确】
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "NormalTransDemo12")]
    [Description("CodeExamples/NormalTransDemo12")]
    public async Task<long> NormalTransDemo12()
    {
        var _trans = _rep.AsTenant();
        try
        {
            await _trans.BeginTranAsync();
 
            await Commomn("", "正常---手写事务");
 
            await _trans.CommitTranAsync();
        }
        catch
        {
            await _trans.RollbackTranAsync();
            throw;
        }
 
        return 1;
    }
 
 
    /// <summary>
    /// 正常---手写事务,tran对象不一样    【正确写法】【正确】
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "NormalTransDemo122")]
    [Description("CodeExamples/NormalTransDemo122")]
    public async Task<long> NormalTransDemo122()
    {
        var _trans = _rep.AsTenant();
        try
        {
            await _trans.BeginTranAsync();
 
            await Commomn("", "正常---手写事务");
 
            await _repTeacher.AsTenant().CommitTranAsync();
        }
        catch
        {
            await _repTeacher.AsTenant().RollbackTranAsync();
            throw;
        }
 
        return 1;
    }
 
 
    /// <summary>
    /// 异常---无事务-未保存就抛异常
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "ExceptionTransDemo21")]
    [Description("CodeExamples/ExceptionTransDemo21")]
    public async Task<long> ExceptionTransDemo21()
    {
        await Commomn("未保存就抛异常", "异常---无事务-未保存就抛异常");
 
        return 1;
    }
    /// <summary>
    /// 异常---无事务-保存第一个就抛异常
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "ExceptionTransDemo22")]
    [Description("CodeExamples/ExceptionTransDemo22")]
    public async Task<long> ExceptionTransDemo22()
    {
        //现象:老师表增加了数据,学生表没增加数据
        await Commomn("保存第一个就抛异常", "异常---无事务-保存第一个就抛异常");
 
        return 1;
    }
    /// <summary>
    /// 异常---无事务-保存第二个就抛异常
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "ExceptionTransDemo23")]
    [Description("CodeExamples/ExceptionTransDemo23")]
    public async Task<long> ExceptionTransDemo23()
    {
        //现象:老师表和学生表都增加了数据
        await Commomn("保存第二个就抛异常", "异常---无事务-保存第二个就抛异常");
 
        return 1;
    }
 
 
    /// <summary>
    /// 异常---特性事务-未保存就抛异常   【正确写法】【正确】
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "ExceptionTransDemo1")]
    [Description("CodeExamples/ExceptionTransDemo1")]
    [UnitOfWork]
    public async Task<long> ExceptionTransDemo1()
    {
        await Commomn("未保存就抛异常", "异常---特性事务-未保存就抛异常");
 
        return 1;
    }
    /// <summary>
    /// 异常---特性事务-保存第一个就抛异常   【正确写法】【正确】
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "ExceptionTransDemo2")]
    [Description("CodeExamples/ExceptionTransDemo2")]
    [UnitOfWork]
    public async Task<long> ExceptionTransDemo2()
    {
        await Commomn("保存第一个就抛异常", "异常---特性事务-保存第一个就抛异常");
 
        return 1;
    }
    /// <summary>
    /// 异常---特性事务-保存第二个就抛异常   【正确写法】【正确】
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "ExceptionTransDemo3")]
    [Description("CodeExamples/ExceptionTransDemo3")]
    [UnitOfWork]
    public async Task<long> ExceptionTransDemo3()
    {
        //Thread.Sleep(10 * 1000);
 
        await Commomn("保存第二个就抛异常", "异常---特性事务-保存第二个就抛异常");
 
        return 1;
    }
 
    /// <summary>
    /// 异常---手写事务-未保存就抛异常   【没有影响表】【正确】
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "ExceptionTransDemo11")]
    [Description("CodeExamples/ExceptionTransDemo11")]
    public async Task<long> ExceptionTransDemo11()
    {
        //现象:无影响,没有影响表
        _rep.AsSugarClient().AsTenant().BeginTran();
        await Commomn("未保存就抛异常", "异常---手写事务-未保存就抛异常");
        _rep.AsSugarClient().AsTenant().CommitTran();
        return 1;
    }
 
 
 
    #region 异常---手写事务-保存第一个就抛异常
 
    /// <summary>
    /// 异常---手写事务-保存第一个就抛异常   【没写RollbackTranAsync】【异常】
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "ExceptionTransDemo12")]
    [Description("CodeExamples/ExceptionTransDemo12")]
    public async Task<long> ExceptionTransDemo12()
    {
        //没写RollbackTranAsync
        //现象:老师表会锁表,学生表不会锁
        await _rep.AsTenant().BeginTranAsync();
        await Commomn("保存第一个就抛异常", "异常---手写事务-保存第一个就抛异常");
        await _rep.AsTenant().CommitTranAsync();
        return 1;
    }
 
    /// <summary>
    /// 异常---手写事务-保存第一个就抛异常   【没写BeginTranAsync】【异常】
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "ExceptionTransDemo1287")]
    [Description("CodeExamples/ExceptionTransDemo1287")]
    public async Task<long> ExceptionTransDemo1287()
    {
        // 没写 BeginTranAsync
        //现象:老师表数据写进去了,学生表没有写进去,没有锁表,事务没有回滚
        try
        {
            await Commomn("保存第一个就抛异常", "异常---手写事务-保存第一个就抛异常");
            await _rep.AsTenant().CommitTranAsync();
            return 1;
        }
        catch
        {
            await _rep.AsTenant().RollbackTranAsync();
            throw;
        }
        //*/
    }
 
    /// <summary>
    /// 异常---手写事务-保存第一个就抛异常   【正确写法】【正确】
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "ExceptionTransDemo999")]
    [Description("CodeExamples/ExceptionTransDemo999")]
    public async Task<long> ExceptionTransDemo999()
    {
 
        // 正确写法
        //现象:正常报错,没有锁表,事务回滚
        try
        {
            await _rep.AsTenant().BeginTranAsync();
            await Commomn("保存第一个就抛异常", "异常---手写事务-保存第一个就抛异常");
            await _rep.AsTenant().CommitTranAsync();
            return 1;
        }
        catch
        {
            await _rep.AsTenant().RollbackTranAsync();
            throw;
        }
        //*/
    }
 
    #endregion
 
 
    #region 异常---手写事务-保存第二个就抛异常
 
    /// <summary>
    /// 异常---手写事务-保存第二个就抛异常 【没写RollbackTran】【异常】
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "ExceptionTransDemo13")]
    [Description("CodeExamples/ExceptionTransDemo13")]
    public async Task<long> ExceptionTransDemo13()
    {
        //没写RollbackTran
        //现象:老师表和学生表都会锁表
        await _rep.AsTenant().BeginTranAsync();
        await Commomn("保存第二个就抛异常", "异常---手写事务-保存第二个就抛异常");
        await _rep.AsTenant().CommitTranAsync();
        return 1;
 
        //*/
    }
 
    /// <summary>
    /// 异常---手写事务-保存第二个就抛异常  【没写BeginTranAsync】【异常】
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "ExceptionTransDemo1213")]
    [Description("CodeExamples/ExceptionTransDemo1213")]
    public async Task<long> ExceptionTransDemo1213()
    {
        //没写BeginTranAsync
        //现象:两个表数据都写进去了,没有锁表,事务没有回滚
        try
        {
            await Commomn("保存第二个就抛异常", "异常---手写事务-保存第二个就抛异常");
            await _rep.AsTenant().CommitTranAsync();
            return 1;
        }
        catch
        {
            await _rep.AsTenant().RollbackTranAsync();
            throw;
        }
        //*/
    }
 
    /// <summary>
    /// 异常---手写事务-保存第二个就抛异常  【正确写法】【正确】
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "ExceptionTransDemo123")]
    [Description("CodeExamples/ExceptionTransDemo123")]
    public async Task<long> ExceptionTransDemo123()
    {
        //var bb = "111";
        //Thread.Sleep(10*1000);
        // 正确写法
        //现象:正常报错,没有锁表,事务正常回滚
        try
        {
            await _rep.AsTenant().BeginTranAsync();
            await Commomn("保存第二个就抛异常", "异常---手写事务-保存第二个就抛异常");
            await _rep.AsTenant().CommitTranAsync();
            return 1;
        }
        catch
        {
            await _rep.AsTenant().RollbackTranAsync();
            throw;
        }
        //*/
    }
 
    #endregion
 
 
 
    private async Task Commomn(string flagName, string remark)
    {
        var pre = remark + "_";
        //新增老师表
        //新增学生表
        TestTeacher testTeacher = new TestTeacher()
        {
            AliName = pre + "老师测试事务-" + YitIdHelper.NextId().ToString(),
            Name = pre + "老师测试事务-" + YitIdHelper.NextId().ToString(),
        };
        TestStudent testStudent = new TestStudent()
        {
            TeacherName = testTeacher.Name,
            TeacherId = testTeacher.Id,
            AliName = pre + "学生测试事务-" + YitIdHelper.NextId().ToString(),
            Name = pre + "学生测试事务-" + YitIdHelper.NextId().ToString(),
        };
 
        if (flagName == "未保存就抛异常")
        {
            throw Oops.Oh(flagName);
        }
 
        await _repTeacher.InsertAsync(testTeacher);
 
        if (flagName == "保存第一个就抛异常")
        {
            throw Oops.Oh(flagName);
        }
 
        await _rep.InsertAsync(testStudent);
 
        if (flagName == "保存第二个就抛异常")
        {
            throw Oops.Oh(flagName);
        }
    }
 
    /// <summary>
    /// 删除测试学生表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    [Description("CodeExamples/Delete")]
    public async Task Delete(DeleteTestStudentInput input)
    {
        var entity = await _rep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        //await _rep.FakeDeleteAsync(entity);   //假删除
        await _rep.DeleteAsync(entity);   //真删除
    }
 
    /// <summary>
    /// 更新测试学生表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    [Description("CodeExamples/Update")]
    public async Task Update(UpdateTestStudentInput input)
    {
        var entity = input.Adapt<TestStudent>();
 
        //重复性验证
        await CheckExist(entity, true);
 
        await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }
 
    /// <summary>
    /// 获取测试学生表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    [Description("CodeExamples/Detail")]
    public async Task<TestStudent> Detail([FromQuery] QueryByIdTestStudentInput input)
    {
        return await _rep.GetFirstAsync(u => u.Id == input.Id);
    }
 
    /// <summary>
    /// 获取测试学生表列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    [Description("CodeExamples/List")]
    public async Task<List<TestStudentOutput>> List([FromQuery] TestStudentInput input)
    {
        return await _rep.AsQueryable().Select<TestStudentOutput>().ToListAsync();
    }
 
 
 
 
    #region 私有方法
 
    /// <summary>
    /// 重复性验证
    /// </summary>
    /// <param name="input">验证对象</param>
    /// <param name="isEdit">是否是编辑</param>
    /// <returns></returns>
    private async Task CheckExist(TestStudent input, bool isEdit = false)
    {
 
 
 
        //没有配置组合校验,不需要验重
 
 
        //没有配置单独校验,不需要验重
    }
    #endregion
 
}