mirror of
https://github.com/dotnetcore/FreeSql.git
synced 2026-02-09 01:40:56 +08:00
update
43
DbContext.md
43
DbContext.md
@@ -158,6 +158,49 @@ db.Add(new Xxx());
|
||||
|
||||
Guid Id 的情况下,执行三次命令:前两次插入合并执行,update 为一次,后面的 add 为一次。
|
||||
|
||||
## 联级保存
|
||||
|
||||
```csharp
|
||||
class Cagetory
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
|
||||
[Navigate("CagetoryId")]
|
||||
public List<Goods> Goodss { get; set; }
|
||||
}
|
||||
class Goods
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public Guid CagetoryId { get; set; }
|
||||
}
|
||||
```
|
||||
|
||||
上面是【一对多】模型, Catetory 保存时可联级保存 Goodss 集合。出于使用安全考虑我们没做完整对比,只实现 Goodss 集合的添加或更新操作,所以不会删除 Goods 的数据。
|
||||
|
||||
完整对比的功能使用起来太危险,试想下面的场景:
|
||||
|
||||
- 保存 Cagetory 的时候,Goodss 是个空列表,如何操作?记录全部删除?
|
||||
- 保存 Category 的时候,由于数据库中 Goodss 记录非常之多,那么只想保存 Goodss 部分数据,或者只需要添加,如何操作?
|
||||
|
||||
【多对多】模型下,我们对中间表的保存是完整对比操作,对外部实现的操作只作新增(注意不会更新)。
|
||||
|
||||
- 属性集合为空时,删除他们的所有关联数据(中间表)
|
||||
- 属性集合不为空时,与数据库存在的数据完全对比,计算出应该删除和添加的记录
|
||||
|
||||
如何关闭联级保存功能?
|
||||
|
||||
全局关闭:
|
||||
|
||||
```csharp
|
||||
fsql.SetDbContextOptions(opt => opt.EnableAddOrUpdateNavigateList = false);
|
||||
```
|
||||
|
||||
局部关闭:
|
||||
```csharp
|
||||
var repo = fsql.GetRepository<T>();
|
||||
repo.DbContextOptions = new DbContextOptions { EnableAddOrUpdateNavigateList = false };
|
||||
```
|
||||
## 参考资料
|
||||
|
||||
- [《分区、分表、分库》](https://github.com/2881099/FreeSql/wiki/%e5%88%86%e5%8c%ba%e5%88%86%e8%a1%a8)
|
||||
|
||||
Reference in New Issue
Block a user