mirror of
https://github.com/dotnetcore/FreeSql.git
synced 2026-02-04 23:40:53 +08:00
Updated Unit of Work (markdown)
@@ -1,41 +1,43 @@
|
||||
[中文](%e5%b7%a5%e4%bd%9c%e5%8d%95%e5%85%83) | **English**
|
||||
|
||||
UnitOfWork 可将多个仓储放在一个单元管理执行,最终通用 Commit 执行所有操作,内部采用了数据库事务;
|
||||
Unit of work can put multiple repositories into one unit for internal management and execution, and finally execute all operations through `Commit`. Unit of work internally uses database transactions.
|
||||
|
||||
```csharp
|
||||
static IFreeSql fsql = new FreeSql.FreeSqlBuilder()
|
||||
.UseConnectionString(FreeSql.DataType.MySql, connectionString)
|
||||
.UseAutoSyncStructure(true) //自动同步实体结构到数据库
|
||||
.Build(); //请务必定义成 Singleton 单例模式
|
||||
.UseConnectionString(FreeSql.DataType.MySql, connectionString)
|
||||
//Automatically synchronize the entity structure to the database.
|
||||
.UseAutoSyncStructure(true)
|
||||
//Be sure to define as singleton mode
|
||||
.Build();
|
||||
```
|
||||
|
||||
## 如何使用
|
||||
## Usage
|
||||
|
||||
```csharp
|
||||
using (var uow = fsql.CreateUnitOfWork())
|
||||
{
|
||||
var songRepo = fsql.GetRepository<Song>();
|
||||
var userRepo = fsql.GetRepository<User>();
|
||||
songRepo.UnitOfWork = uow; //手工绑定工作单元
|
||||
songRepo.UnitOfWork = uow; //Manually bind unit of work
|
||||
userRepo.UnitOfWork = uow;
|
||||
|
||||
songRepo.Insert(new Song());
|
||||
userRepo.Update(...);
|
||||
|
||||
uow.Orm.Insert(new Song()).ExecuteAffrows();
|
||||
//注意:uow.Orm 和 fsql 都是 IFreeSql
|
||||
//uow.Orm CRUD 与 uow 是一个事务(理解为临时 IFreeSql)
|
||||
//fsql CRUD 与 uow 不在一个事务
|
||||
//Note: uow.Orm and fsql are both IFreeSql
|
||||
//uow.Orm CRUD and uow are the same transaction (understood as temporary IFreeSql)
|
||||
//fsql CRUD and uow are not in the same transaction
|
||||
|
||||
uow.Commit();
|
||||
}
|
||||
```
|
||||
|
||||
参考:[在 asp.net core 中使用 TransactionalAttribute + UnitOfWorkManager 实现多种事务传播](https://github.com/dotnetcore/FreeSql/issues/289)
|
||||
Reference: [Use TransactionalAttribute + UnitOfWorkManager in ASP.NET Core to achieve multiple transaction propagation](https://github.com/dotnetcore/FreeSql/issues/289)
|
||||
|
||||
## 接口定义
|
||||
## Interface Definition
|
||||
|
||||
uow.GetOrBeginTransaction() 方法可获取事务对象。
|
||||
The `uow.GetOrBeginTransaction()` method can get the transaction object.
|
||||
|
||||
```csharp
|
||||
public interface IUnitOfWork : IDisposable
|
||||
|
||||
Reference in New Issue
Block a user