update

28810
2020-04-20 07:42:55 +08:00
parent 128ade668c
commit 9e03635929

@@ -150,118 +150,10 @@ Task<TEntity> InsertAsync(TEntity entity);
* 避免使用数据库的默认值功能;
* 仓储层实现请使用 GuidRepository
## UnitOfWork
UnitOfWork 可将多个仓储放在一个单元管理执行,最终通用 Commit 执行所有操作,内部采用了数据库事务;
```csharp
using (var uow = fsql.CreateUnitOfWork()) {
var songRepo = uow.GetRepository<Song>();
var userRepo = uow.GetRepository<User>();
//上面两个仓储由同一UnitOfWork uow 创建
//在此执行仓储操作
//这里不受异步方便影响
uow.Commit();
}
```
参考:在 asp.net core 中注入工作单元方法
```csharp
//第一步:
public class UnitOfWorkRepository<TEntity, TKey> : BaseRepository<TEntity, TKey>
{
public UnitOfWorkRepository(IFreeSql fsql, IUnitOfWork uow) : base(fsql, null, null)
{
this.UnitOfWork = uow;
}
}
public class UnitOfWorkRepository<TEntity> : BaseRepository<TEntity, int>
{
public UnitOfWorkRepository(IFreeSql fsql, IUnitOfWork uow) : base(fsql, null, null)
{
this.UnitOfWork = uow;
}
}
//第二步:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IFreeSql>(fsql);
services.AddScoped<FreeSql.IUnitOfWork>(sp => fsql.CreateUnitOfWork());
services.AddScoped(typeof(IBaseRepository<>), typeof(UnitOfWorkRepository<>));
services.AddScoped(typeof(BaseRepository<>), typeof(UnitOfWorkRepository<>));
//批量注入程序集内的所有自建仓储类,可以根据自己需要来修改
Assembly[] assemblies = new [] { typeof(XxxRepository).Assembly };
if (assemblies?.Any() == true)
foreach (var asse in assemblies)
foreach (var repo in asse.GetTypes().Where(a => a.IsAbstract == false && typeof(UnitOfWorkRepository).IsAssignableFrom(a)))
services.AddScoped(repo);
}
```
## 联级保存
请移步文档[《联级保存》](https://github.com/2881099/FreeSql/wiki/%e8%81%94%e7%ba%a7%e4%bf%9d%e5%ad%98)
## 实体变化事件
全局设置:
```csharp
fsql.SetDbContextOptions(opt => {
opt.OnEntityChange = report => {
Console.WriteLine(report);
};
});
```
单独设置 DbContext 或者 UnitOfWork
```csharp
var ctx = fsql.CreateDbContext();
ctx.Options.OnEntityChange = report => {
Console.WriteLine(report);
};
var uow = fsql.CreateUnitOfWork();
uow.OnEntityChange = report => {
Console.WriteLine(report);
};
```
参数 report 是一个 List 集合,集合元素的类型定义如下:
```csharp
public class EntityChangeInfo
{
public object Object { get; set; }
public EntityChangeType Type { get; set; }
}
public enum EntityChangeType { Insert, Update, Delete, SqlRaw }
```
| 变化类型 | 说明 |
| -- | -- |
| Insert | 实体对象被插入 |
| Update | 实体对象被更新 |
| Delete | 实体对象被删除 |
| SqlRaw | 执行了SQL语句 |
SqlRaw 目前有两处地方比较特殊:
- 多对多联级更新导航属性的时候,对中间表的全部删除操作;
- 通用仓储类 BaseRepository 有一个 Delete 方法,参数为表达式,而并非实体;
```csharp
int Delete(Expression<Func<TEntity, bool>> predicate);
```
DbContext.SaveChanges或者 Repository 对实体的 Insert/Update/Delete或者 UnitOfWork.Commit 操作都会最多触发一次该事件。
## API
| 属性 | 返回值 | 说明 |