C# Linq关联Customer与Payment表查询2021年无支付记录客户
原有代码的问题
- 语法错误:join子句后应该使用
in关键字而非from - 逻辑错误:直接关联后再筛选支付年份,会提前过滤掉本身没有任何支付记录的客户,且
into分组后的计数调用写法也不正确,无法得到预期结果。
正确实现方式
方式1:查询语法(左连接实现)
using System.Linq; var result = from customer in context.Customers // 先过滤出2021年的支付记录再做左连接 join payment in context.Payments.Where(p => p.Year == 2021) on customer.CustomerId equals payment.CustomerId into customerPayments // 筛选没有匹配到2021年支付记录的客户 where !customerPayments.Any() select customer;
方式2:方法语法(NOT EXISTS逻辑,更简洁高效)
using System.Linq; var result = context.Customers .Where(c => !context.Payments.Any(p => p.CustomerId == c.CustomerId && p.Year == 2021)) .ToList();
该写法最终生成的SQL是标准的NOT EXISTS查询,执行效率更高,逻辑也更直观。
内容的提问来源于stack exchange,提问作者Emre
相关产品推荐
相关产品推荐

