更新主体实体时如何正确删除从属实体?
How do you properly delete Dependent entites when updating the Principal entity?
我在使用 EFCore 2.0 时遇到问题,在更新主实体时无法正确删除依赖实体。这是我的代码:
映射
public class BlueprintMap : IEntityTypeConfiguration<Blueprint>
{
public void Configure(EntityTypeBuilder<Blueprint> builder)
{
builder.ToTable("blueprint").HasKey(t => t.Id);
builder.Property(x => x.Id).HasColumnName("blueprint_id").ValueGeneratedOnAdd();
builder.HasMany<Objective>().WithOne(x => x.Blueprint).OnDelete(DeleteBehavior.Cascade);
}
}
public class ObjectiveMap : IEntityTypeConfiguration<Objective>
{
public void Configure(EntityTypeBuilder<Objective> builder)
{
builder.ToTable("objective").HasKey(x => x.Id);
builder.Property(x => x.Id).HasColumnName("objective_id").ValueGeneratedOnAdd();
builder.HasOne(x => x.Blueprint).WithMany(y => y.Objectives).HasForeignKey("blueprint_id");
}
}
更新 WebApi 调用
从上下文中获取
var blueprint = await blueprintContext.Blueprints
.Where(x => id == x.Id)
.Include(x => x.Objectives)
.SingleOrDefaultAsync();
从蓝图实体中移除目标(目标是 ICollection,依赖实体
blueprint.Objectives.Remove(objective);
// 获取新上下文
var blueprintContext = await _blueprintContextFactory.CreateContext();
上下文中的蓝图实体和蓝图有 0 个目标
int x = await blueprintContext.SaveChangesAsync();
获取 WebApi 调用
从上下文中获取
return await blueprintContext.Blueprints
.Where(x => id == x.Id)
.Include(x => x.Objectives)
.SingleOrDefaultAsync();
蓝图又有 2 个目标。
愚蠢的错误。第一个上下文跟踪被删除的目标。当生成新上下文以保存更改时,它不知道目标被删除,因此它们会保留并重新生成。换句话说,更新请求使用多个上下文,而不是每个请求仅使用 1 个上下文,这是 EF Core 设计不能接受的。
我在使用 EFCore 2.0 时遇到问题,在更新主实体时无法正确删除依赖实体。这是我的代码:
映射
public class BlueprintMap : IEntityTypeConfiguration<Blueprint>
{
public void Configure(EntityTypeBuilder<Blueprint> builder)
{
builder.ToTable("blueprint").HasKey(t => t.Id);
builder.Property(x => x.Id).HasColumnName("blueprint_id").ValueGeneratedOnAdd();
builder.HasMany<Objective>().WithOne(x => x.Blueprint).OnDelete(DeleteBehavior.Cascade);
}
}
public class ObjectiveMap : IEntityTypeConfiguration<Objective>
{
public void Configure(EntityTypeBuilder<Objective> builder)
{
builder.ToTable("objective").HasKey(x => x.Id);
builder.Property(x => x.Id).HasColumnName("objective_id").ValueGeneratedOnAdd();
builder.HasOne(x => x.Blueprint).WithMany(y => y.Objectives).HasForeignKey("blueprint_id");
}
}
更新 WebApi 调用
从上下文中获取
var blueprint = await blueprintContext.Blueprints
.Where(x => id == x.Id)
.Include(x => x.Objectives)
.SingleOrDefaultAsync();
从蓝图实体中移除目标(目标是 ICollection,依赖实体
blueprint.Objectives.Remove(objective);
// 获取新上下文
var blueprintContext = await _blueprintContextFactory.CreateContext();
上下文中的蓝图实体和蓝图有 0 个目标
int x = await blueprintContext.SaveChangesAsync();
获取 WebApi 调用
从上下文中获取
return await blueprintContext.Blueprints
.Where(x => id == x.Id)
.Include(x => x.Objectives)
.SingleOrDefaultAsync();
蓝图又有 2 个目标。
愚蠢的错误。第一个上下文跟踪被删除的目标。当生成新上下文以保存更改时,它不知道目标被删除,因此它们会保留并重新生成。换句话说,更新请求使用多个上下文,而不是每个请求仅使用 1 个上下文,这是 EF Core 设计不能接受的。