为什么此Linq查询返回的结果与SQL等效的结果不同?

时间:2018-09-12 18:07:59

标签: sql linq

我确定我缺少一些简单的东西,但这里有一个linq查询:

 public static List<Guid> GetAudience()
    {
        var createdOn = new DateTime(2018, 6, 30, 0, 0, 0);
        var x = new List<Guid>();

        try
        {
            var query = from acc in Account
                where acc.num != null
                      && acc.StateCode.Equals(0)
                      && acc.CreatedOn < createdOn
                select new
                {
                    acc.Id
                };

            foreach (var z in query)
            {
                if (z.Id != null)
                {
                    x.Add(z.Id.Value);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        return x;
    }

我想验证SQL中的计数,因为它只需要几秒钟,所以:

select count(*)
from Account a
where a.num is not null
and a.statecode = 0
and a.createdon < '2018-06-30 00:00:00'

现在,SQL查询返回9,329,而Linq返回10,928。当查询做同样的事情时(为什么我这么认为),我的计数为什么这么远?我缺少什么简单的东西?

预先感谢-

1 个答案:

答案 0 :(得分:1)

您的方法正在返回记录列表,其中Id值不为null(加上其他条件)。 SQL查询返回记录数的计数(加上其他条件)。没有表的定义,很难知道这是否有意义。

不相关的提示:捕获并吞下这样的异常不是一个好主意-方法的调用者将不知道任何错误,因此处理将继续;但是它将使用不完整的数据,可能在以后的程序中导致其他问题。