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

EF Core查询中Count()返回1但结果视图显示0的问题排查

EF Core异常:Count()/Any()返回1但实际无记录

问题情况

CustomerNation表无任何记录,但代码中Count()与Any()均返回存在1条记录,调试时结果视图显示0条。

相关代码

查询用户数据代码

var user = await context.Customers
                .Include(x => x.CustomerPreferences)
                .ThenInclude(up => up.CustomerNations)
                .Where(x => x.Id == userId).FirstOrDefaultAsync(cancellationToken);

Customer实体定义

public Customer Customer { get; set; } = null!;
public virtual IList<CustomerNation> CustomerNations { get; set; } = new List<CustomerNation>();

后续处理代码

var preferences= user.preferences
                .ToList();

if (preferences.Any())
{
    var customerNations= user.CustomerPreferences
        .Select(x => x.CustomerNations);

    if (customerNations.Count() != 0) //Count()和Any()均显示有1条记录,但结果视图显示0条
    {
        foreach (var nation in customerNations)
        {
            context.Remove(counterParty);
        }
    }
}

问题原因

你用Select(x => x.CustomerNations)得到的是IEnumerable<IList<CustomerNation>>,也就是每个CustomerPreference对应的CustomerNations列表的集合。此时Count()统计的是CustomerPreference的数量,而非CustomerNation的记录数——哪怕某个CustomerPreference的CustomerNations是空列表,它也会被算成1个元素,所以出现Count返回1但实际无数据的情况。

解决方法

  1. 替换Select为SelectMany,将嵌套的集合扁平化,得到所有CustomerNation的集合:
var customerNations= user.CustomerPreferences
    .SelectMany(x => x.CustomerNations);
  1. 此时调用Count()或Any()就能得到实际的CustomerNation记录数。

另外修正代码中的两处错误:

  • user.preferences改为user.CustomerPreferences(匹配实体定义)
  • 循环中的context.Remove(counterParty)改为context.Remove(nation)(移除正确对象)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 18:20:59