关注系统接口返回Null排查:数据库存在请求但无结果
问题排查及解决方案
1. 导航属性逻辑混淆
你的AppUser类中导航属性的命名和实际业务含义不匹配,直接导致查询方向错误:
Follower集合应代表关注当前用户的人(即当前用户是被关注者,对应FollowUser表中FollowingId = 当前用户ID的记录)Following集合应代表当前用户主动关注的人(即当前用户是发起关注的一方,对应FollowUser表中FollowerId = 当前用户ID的记录)
你在接口中错误地从u.Following集合查询待处理请求,这相当于查找"当前用户主动关注的人里的待审核请求",但实际待处理请求是"他人请求关注当前用户",应该从u.Follower集合中查询。
2. 查询条件冗余且错误
原查询中的Where(f => f.PendingStatus == true && f.FollowingId == userId)存在两个问题:
- 已经通过
SelectMany(u => u.Following)限定了集合范围,再判断f.FollowingId == userId属于冗余条件,且因导航属性逻辑错误,这个条件会过滤掉所有正确数据 - 正确的查询逻辑应针对
Follower集合,仅筛选PendingStatus == true的记录
3. 修复后的接口代码
[HttpGet("follow-requests/{userId}")] public async Task<ActionResult> GetFollowRequests([FromRoute] string userId) { var user = await _userManager.FindByIdAsync(userId); if (user == null) return BadRequest("Failed to find user with the specific id"); // 修正:从Follower集合(关注当前用户的人)中筛选待审核请求 var requests = await _userManager.Users .Where(u => u.Id == userId) .SelectMany(u => u.Follower) .Where(f => f.PendingStatus == true) .ToListAsync(); if (requests.IsNullOrEmpty()) return Ok("You don't have any follow requests"); return Ok(requests); }
4. 验证EF Core关系配置(关键)
确保FollowUser实体的外键关系在EF Core中正确配置,否则导航属性无法正确加载数据。可通过Fluent API在DbContext中配置:
protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // 配置复合主键 modelBuilder.Entity<FollowUser>() .HasKey(f => new { f.FollowerId, f.FollowingId }); // 配置关注者与关注记录的关系 modelBuilder.Entity<FollowUser>() .HasOne(f => f.Follower) .WithMany(u => u.Following) .HasForeignKey(f => f.FollowerId) .OnDelete(DeleteBehavior.Restrict); // 配置被关注者与关注记录的关系 modelBuilder.Entity<FollowUser>() .HasOne(f => f.Following) .WithMany(u => u.Follower) .HasForeignKey(f => f.FollowingId) .OnDelete(DeleteBehavior.Restrict); }
5. 额外优化建议
- 给导航属性重命名,比如将
Follower改为Followers、Following改为Followings,语义更清晰,避免混淆 - 若遇到懒加载导致的数据未加载问题,可在查询时显式添加
Include(u => u.Follower)确保关联数据被加载
内容的提问来源于stack exchange,提问作者Mateus Pedro
相关产品推荐
相关产品推荐

