Ef 核心不跟踪子集合的更改

我有这些模型


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

为什么没有检测到变化?


慕桂英3389331
浏览 252回答 2
2回答

慕容708150

如果你改变:&nbsp;var warehouseAllocation = dbContext.WarehouseAllocations&nbsp;.Include(w => w.Dispatches)&nbsp;.SingleOrDefault(w => w.Id == warehouseAllocationId);到:&nbsp;var warehouseAllocation = dbContext.WarehouseAllocations&nbsp;.Include(w => w.Dispatches)&nbsp;.ThenInclude(d => d.DispatchDetail)&nbsp;.SingleOrDefault(w => w.Id == warehouseAllocationId);它应该通知 EF 您希望将 DispatchDetail 包含到其更改跟踪器中。这也DispatchDetail将从数据库中提取w 的所有值。
打开App,查看更多内容
随时随地看视频慕课网APP