EF Core 9升级后操作DDD聚合根出现并发更新异常求助
问题排查与解决方案
1. 并发令牌配置问题
EF Core 9对并发检查的严格性有所提升,若Post聚合根的并发令牌(如RowVersion或手动维护的版本号)配置不当,或添加/修改Comment时未同步更新聚合根的并发令牌,会触发该异常。
- 检查
PostConfiguration中是否正确配置数据库自动生成的并发令牌:builder.Property(p => p.RowVersion) .IsRowVersion(); // 或使用.IsTimestamp() - 若用手动维护的版本号作为并发令牌,确保在Post的
AddComment/UpdateComment方法中显式更新:public void AddComment(Comment comment) { Comments.Add(comment); Version++; // Version为聚合根的并发版本属性 }
2. 聚合根跟踪状态问题
EF Core 9处理关联实体变更时,可能未自动将聚合根标记为Modified状态。仅修改Comment时,EF会跟踪Comment的变更,但Post的并发检查仍会执行,若内存中Post的状态未更新,会导致数据库版本号不匹配。
- 在命令处理器中,操作Comment后显式标记Post为修改状态:
public async Task<Guid> Handle(AddCommentToPostCommand command, CancellationToken cancellationToken) { var post = await _postRepository.GetByIdAsync(command.PostId, cancellationToken); post.AddComment(command.CommentContent); _dbContext.Entry(post).State = EntityState.Modified; await _postRepository.UnitOfWork.SaveChangesAsync(cancellationToken); return post.Id; }
3. 关联实体变更跟踪逻辑变化
EF Core 9优化了集合导航属性的变更跟踪,若Comment的主键生成策略或关联配置有误,会导致EF无法正确识别聚合根的变更。
- 检查
PostConfiguration中Comments集合的关联配置:builder.HasMany(p => p.Comments) .WithOne() .HasForeignKey(c => c.PostId) .OnDelete(DeleteBehavior.Cascade); - 确保Comment的主键配置为数据库自动生成(若使用自增主键):
builder.Property(c => c.Id) .ValueGeneratedOnAdd();
4. 实体加载跟踪问题
若命令处理器中用AsNoTracking加载Post,EF无法跟踪聚合根的状态变更,会触发并发异常。
- 确保加载Post时使用跟踪查询,或手动附加实体并设置状态:
var post = await _dbContext.Posts.AsTracking().FirstOrDefaultAsync(p => p.Id == command.PostId, cancellationToken);
内容的提问来源于stack exchange,提问作者arman
相关产品推荐
相关产品推荐

