You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Instagram风格关注列表排序查询实现异常,请求排查修正

问题分析

你的代码核心问题是排序逻辑不符合需求,还存在语法错误和查询可靠性问题:

  1. 排序逻辑失效:用Union拼接集合无法保证「A→共同关注→其他」的优先级顺序,因为Union仅保留第一个集合的原有排序(你之前是按创建时间降序),没有区分三类用户的优先级。
  2. 未单独提取目标用户A:没有从B的关注列表里筛选出A并放在首位。
  3. 语法错误:在finalQueryResult定义前就调用CountAsync(),会导致编译报错。
  4. 交集查询不可靠:EF的Intersect依赖实体的相等性配置,若ChannelMember未正确设置主键,可能无法得到正确的共同关注列表。
修正后的代码
// 当前请求用户A的ID
var currentUserId = requestingUserId.Value;
// 被查看用户B的ID
var targetUserId = request.RequestedUserId;

// 1. 查询B的所有关注列表(B作为关注者,MemberUserId=B的ID)
var allBFollowings = repository_.ChannelMemberReadOnly()
    .Where(c => c.MemberUserId == targetUserId)
    .Include(c => c.ChannelInfo)
    .ThenInclude(c => c.User);

// 2. 筛选B关注的A(如果存在)
var userAFollowedByB = allBFollowings
    .Where(c => c.ChannelInfo.User.Id == currentUserId);

// 3. 查询A的所有关注用户ID,用于匹配共同关注(只查ID提升性能)
var allAFollowingUserIds = repository_.ChannelMemberReadOnly()
    .Where(c => c.MemberUserId == currentUserId)
    .Select(c => c.ChannelInfo.User.Id);

// 4. 筛选B和A的共同关注(排除A自己)
var commonFollowings = allBFollowings
    .Where(c => allAFollowingUserIds.Contains(c.ChannelInfo.User.Id) 
                && c.ChannelInfo.User.Id != currentUserId);

// 5. 筛选B的其他关注(排除A和共同关注)
var remainingFollowings = allBFollowings
    .Where(c => c.ChannelInfo.User.Id != currentUserId 
                && !allAFollowingUserIds.Contains(c.ChannelInfo.User.Id));

// 6. 按优先级拼接+保留原创建时间降序:A→共同关注→其他
var finalQueryResult = userAFollowedByB
    .Concat(commonFollowings)
    .Concat(remainingFollowings)
    .OrderByDescending(c => c.DateCreated);

// 获取总数量(必须在分页前执行)
var totalCount = await finalQueryResult.CountAsync();

// 分页并转换为API模型
var followings = await finalQueryResult
    .PerPage(request.Page, request.PerPage)
    .Select(c => ConvertModelToApi.ToApi(configuration_, c.ChannelInfo.User))
    .ToListAsync();

return new()
{
    Total = totalCount,
    Followings = followings
};
关键修正说明
  • 优先级排序:用Concat替代Union,确保三个集合按需求顺序拼接(通过筛选条件保证了三个集合无重叠,无需去重)。
  • 可靠的共同关注查询:用Contains替代Intersect,直接通过用户ID匹配,避免实体相等性配置问题,同时减少数据传输量。
  • 语法错误修复:将CountAsync()移到finalQueryResult定义之后,且放在分页前执行(分页后Count会返回当前页数量,而非总数)。
  • 清晰的筛选逻辑:拆分三类用户的筛选条件,确保边界明确,不会出现重复或遗漏。

内容的提问来源于stack exchange,提问作者Aiikemefuna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 06:25:22