LINQ查询未按预期查询

时间:2013-05-07 04:59:10

标签: c# linq-to-sql

如果有人可以向我解释为什么这个查询不像SQL Left连接那样,我在徘徊,我似乎无法解决原因。我一直在做一些打猎,我似乎无法解决这个问题。据我所知,它应该 即在一个包含5个活跃客户的表中,它将仅返回其中2个客户而不是全部5个; 2带有值,3带有null或0?

var results = from c in DataContext.Customers
              where c.Active
              join j1 in
              (from i in DataContext.Invoice where i.State== "Pending" &&
               i.InvoiceDate.Date >= From.Date && i.InvoiceDate.Date <= To.Date 
               group i by i.Customer into x 
                      select new { x.Key, Total = x.Count() }) on a equals j1.Key
                      select new { c, j1.Total };

由于

2 个答案:

答案 0 :(得分:1)

通过使用DefaultIfEmpty()方法,您可以执行此操作。 试试这个代码 我已经实现了你的问题的解决方案 如果有效的话还原我

var results = from c in DataContext.Customers
                  where c.Active
                  join j1 in
                  (from i in DataContext.Invoice where i.State== "Pending" &&
                   i.InvoiceDate.Date >= From.Date && i.InvoiceDate.Date <= To.Date 
                   group i by i.Customer into x 
                          select new { x.Key, Total = x.Count() }) on a equals j1.Key into j3
                                from k in j3.DefaultIfEmpty()
                          select new { c, k.Total };

答案 1 :(得分:0)

我会在DefaultIfEmpty()子查询上尝试j1方法,因为您不允许查询加入空值。

有关示例,请参阅similar question