using MediatApi.Entity;using MediatR;using Microsoft.EntityFrameworkCore;using Microsoft.EntityFrameworkCore.Storage;namespace MediatApi.Helper{ public class WyyDbContext: testContext { private IDbContextTransaction _currentTransaction; public IDbContextTransaction GetCurrentTransaction() => _currentTransaction; public bool HasActiveTransaction => _currentTransaction != null; public async Task CommitTransactionAsync(IDbContextTransaction transaction) { if (transaction == null) throw new ArgumentNullException(nameof(transaction)); if (transaction != _currentTransaction) throw new InvalidOperationException($"Transaction {transaction.TransactionId} is not current"); try { await SaveChangesAsync(); transaction.Commit(); } catch { RollbackTransaction(); throw; } finally { if (_currentTransaction != null) { _currentTransaction.Dispose(); _currentTransaction = null; } } } public void RollbackTransaction() { try { _currentTransaction?.Rollback(); } finally { if (_currentTransaction != null) { _currentTransaction.Dispose(); _currentTransaction = null; } } } }}在Program里面注册服务
builder.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(DBTransactionBehavior<,>));这里链接数据库我们做一个新增Command里面的testContext就是数据库上下文我这里是从数据库直接生成的 WyyDbContext继承testContext
using MediatApi.Entity;using MediatR;namespace MediatApi.Application.Command{ public class CusCreateCommand:IRequest<int> { public string? Name { get; set; } public int? Age { get; set; } } public class CusCreateCommandHandler : IRequestHandler<CusCreateCommand, int> { private readonly testContext _db; public CusCreateCommandHandler(testContext db) { _db = db; } public async Task<int> Handle(CusCreateCommand request, CancellationToken cancellationToken) { Cu c = new() { Name = request.Name, Age = request.Age, }; _db.Cus.Add(c); Console.WriteLine("执行处理++++++++++++++++++++++++++++++++++"); return await _db.SaveChangesAsync(); } }}
推荐阅读
- 常用Python库整理
- 加拿大高中排名 加拿大高中排名
- 定位java程序中占用cpu最高的线程堆栈信息
- jk罗琳中文官网 jk罗琳
- PE管十大品牌有哪些 中国pe管道十大品牌
- SpringCloudAlibaba 微服务组件 Nacos 之配置中心源码深度解析
- 幻塔大眼萌仔怎么获取
- 《正义联盟》中超人是怎么死的
- 正义联盟中超人什么时候死的(正义联盟死去的英雄)
- 王者荣耀娜可露露前尘镜中文语音包怎么设置