我在EFCORE 2.0上遇到问题,在更新Prinicipal实体时,它不可能正确删除依赖性实体。这是我的代码:
映射
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();
从蓝图实体中删除目标(目标是偶像,依赖实体
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的设计无法接受的。