我有这些模型。
当我调用
为什么更改没有被检测到?
更新:
在进行更改之后,在调用SaveChanges()之前,为了业务事件,我调用了一个包括仓库分配的LINQ查询。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表中有一个外键WarehouseAllocationId,它指向WarehouseAllocation表。
我使用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 core会检索所有仓库分配及其包含细节的分派。问题在于当我使用这种方法时: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 Core会覆盖当前实体状态吗?
dbContext.Dispatches.Add(new Dispatch...)
吗? - FabioAsNoTracking()
有一点效果,但如果你正在尝试在同一个上下文中进行 Query->Make Changes->Query->Make Changes->Save 操作,我建议将它们拆分为2个上下文,或者使用Unit of Work
模式。 - Adam Vincent