mirror of
https://github.com/dotnetcore/FreeSql.git
synced 2026-02-07 00:40:55 +08:00
update
55
事务.md
55
事务.md
@@ -94,6 +94,61 @@ for update 在 Oracle/PostgreSQL/MySql 是通用的写法,我们对 SqlServer
|
||||
SELECT ... FROM [User] a With(UpdLock, RowLock, NoWait)
|
||||
```
|
||||
|
||||
## 6、示范代码
|
||||
|
||||
```csharp
|
||||
fsql.Transaction(() => //全局线程事务
|
||||
{
|
||||
fsql.Insert(new Products()).ExecuteAffrows();
|
||||
fsql.Insert(new Products()).ExecuteAffrows();
|
||||
});
|
||||
|
||||
using (var uow = fsql.CreateUnitOfWork()) //使用 UnitOfWork 事务
|
||||
{
|
||||
fsql.Insert(new Products()).ExecuteAffrows(); //错误,没有传事务
|
||||
fsql.Insert(new Products()).WithTransaction(uow.GetOrBeginTransaction()).ExecuteAffrows();
|
||||
fsql.Insert(new Products()).WithTransaction(uow.GetOrBeginTransaction()).ExecuteAffrows();
|
||||
|
||||
var repo1 = uow.GetRepository<Products>();
|
||||
repo1.Insert(new Products());
|
||||
}
|
||||
|
||||
using (var ctx = fsql.CreateDbContext()) //使用 DbContext 事务
|
||||
{
|
||||
ctx.Add(new Products());
|
||||
ctx.Add(new Products());
|
||||
|
||||
fsql.Insert(new Products()).ExecuteAffrows(); //错误,没有传事务
|
||||
fsql.Insert(new Products()).WithTransaction(ctx.UnitOfWork.GetOrBeginTransaction()).ExecuteAffrows(); //正常
|
||||
}
|
||||
|
||||
using (var uowManager = new UnitOfWorkManager(fsql)) //使用 UnitOfWorkManager 管理类事务
|
||||
{
|
||||
using (var uow = uowManager.Begin())
|
||||
{
|
||||
fsql.Insert(new Products()).ExecuteAffrows(); //错误,没有传事务
|
||||
fsql.Insert(new Products()).WithTransaction(uow.GetOrBeginTransaction()).ExecuteAffrows();
|
||||
fsql.Insert(new Products()).WithTransaction(uow.GetOrBeginTransaction()).ExecuteAffrows();
|
||||
|
||||
using (var uow2 = uowManager.Begin()) //与 uow 同一个事务
|
||||
{
|
||||
var repo1 = fsql.GetRepository<Products>();
|
||||
repo1.UnitOfWork = uow2;
|
||||
repo1.Insert(new Products());
|
||||
|
||||
uow2.Commit();//事务还未提交
|
||||
}
|
||||
|
||||
uow.Commit();//事务提交
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- IFreeSql curd 方法需要指定 WithTransaction 传递事务;
|
||||
- FreeSql.IBaseRepository curd 方法需要指定 UnitOfWork 传递工作单元事务;
|
||||
- FreeSql.DbContext 自带事务;
|
||||
- UnitOfWorkManager 适合做跨方法事务;
|
||||
|
||||
## 更多资料
|
||||
|
||||
- [《租户》](https://github.com/2881099/FreeSql/wiki/%e7%a7%9f%e6%88%b7)
|
||||
|
||||
Reference in New Issue
Block a user