c# - Ef core 不跟踪子集合的更改
问题描述
我有这些模型
public class WarehouseAllocation
{
public int Id { get; set; }
public Warehouse Warehouse { get; set; }
public IList<Dispatch> Dispatches { get; set; }
//---- removed other properties for brevity
}
public class Dispatch
{
public int Id { get; set; }
public IList<DispatchDetail> DispatchDetails { get; set; }
//---- removed other properties for brevity
}
在数据库上,
Dispatch 具有引用 WarehouseAllocation 表的外键 WarehouseAllocationId 。
我使用 Fluent API 将模型映射到数据库,如下所示:
modelBuilder.Entity<WarehouseAllocation>(m =>
{
m.ToTable("WarehouseAllocation");
m.Property(wa => wa.Id).HasColumnName("WarehouseAllocationId")
.ValueGeneratedOnAdd();
m.HasKey(wa => wa.Id);
m.HasOne(wa => wa.Warehouse)
.WithMany()
.HasForeignKey("WarehouseId");
m.HasMany(w => w.Dispatches)
.WithOne();
});
modelBuilder.Entity<Dispatch>(m =>
{
m.ToTable("Dispatch");
m.Property(wa => wa.Id).HasColumnName("DispatchId")
.ValueGeneratedOnAdd();
m.HasKey(wa => wa.Id);
});
当我调用时
dbContext.WarehouseAllocations .Include(w => w.Dispatches) .ThenInclude(w => w.DispatchDetails).ToList()
,Ef 核心检索所有仓库分配及其调度,包括详细信息。
问题是当我使用这种方法时:
var warehouseAllocation = dbContext.WarehouseAllocations
.Include(w => w.Dispatches)
.ThenInclude(d => d.DispatchDetails)
.SingleOrDefault(w => w.Id == warehouseAllocationId);
warehouseAllocation.Dispatches.Add(new Dispatch
{
//--including other properties
DispatchDetails = new List<DispatchDetail> {
new DispatchDetail
{
//--other properties
}
}
});
// call another query that includes WarehouseAllocation
dbContext.ChangeTracker.HasChanges() // this is false
dbContext.SaveChanges() // this keeps returning zero
为什么没有检测到更改?
更新:
在我进行更改之后并在调用 SaveChanges() 之前,为了业务事件,我调用了一个包含仓库分配的 LINQ 查询。Ef 核心是否会覆盖当前实体状态?
解决方案
问题是,我在调用 SaveChanges() 之前进行了另一个包含仓库分配的查询。
IE
var shipment = _myDbContext.Shipments
.Include(s => s.WarehouseAllocations)
.ThenInclude(s => s.Dispatches)
.ThenInclude(s => s.DispatchDetails)
.Include(s => s.WarehouseAllocations)
.SingleOrDefault(s => s.WarehouseAllocations.Select(w => w.Id).Contains(warheouseAllocationId));
我在 Shipment 上执行一些业务事件逻辑并保存所有更改。(现在我可以以更好的方式做到这一点)
我猜,如果您在保存更改之前进行包含受影响实体类型的查询,Ef 会覆盖实体状态。
推荐阅读
- integration-testing - 如何在赛普拉斯的 before 语句中从夹具文件创建变量?
- sqlite - 如何使用来自 github 的 brew 公式?
- php - Jquery 中 toast 的 Delay 属性在 PHP 构建的站点上不起作用
- python - 如何使用 pandas 在旅途中识别 csv 文件中的日期时间格式?
- asp.net-core - Asp.net core razor pages,身份,外部登录返回错误关联失败
- wpf - Wpf窗口标题栏鼠标活动
- r - 如何绘制数据框列表中每个数据框的条形图
- eeprom - EEPROM页面大小说明
- css - Bootstrap 4(Angular)导航栏折叠按钮不起作用
- sql - 如何更新具有重复 ID 的引用表?