LINQ to SQL - Left OUTER加入两个连接不起作用

时间:2016-09-07 04:07:09

标签: c# linq visual-studio-2015

在以下LINQ查询中,我需要显示All客户,包括尚未下订单但订单价格超过100美元的客户。但我的以下LINQ查询返回所有客户,无论他们的订单价格如何。它似乎忽略了下面LINQ查询中的Where(ord => ord.price > 100)子句。我可能做错了什么?

模型

public class Customer
{
   public int CustomerId { get; set; }
   public string CustName{ get; set; }
}

public class Order
{
   public int OrderId { get; set; }
   public int CustomerId { get; set; }
   public float price  { get; set; }
}

LINQ查询

var Query1 = from c in Customers
             join ord in Orders on c.CustomerId equals ord.CustomerId into cord into cord
             from t in cord.Where(ord => ord.price > 100).DefaultIfEmpty()
             select new {CustName= c.Name, OrderID = (t == null ? 0 : t.OrderId)};

SQL查询

我想将以下T-SQL查询转换为LINQ查询:

SELECT c.Name, OrderID
FROM Customers c
LEFT OUTER JOIN Orders ord
    ON c.CustomerID = ord.CustomerID
    AND ord.Price > 100

1 个答案:

答案 0 :(得分:0)

好吧,我没有你的数据能够验证这一点,但是一个突然出现的问题是你没有指定加入这两个集合的字段(CustomerId)。

尝试修改您的查询:(添加on c.CustomerId equals ord.CustomerId

var Query1 = from c in Customers
             join ord in Orders on c.CustomerId equals ord.CustomerId into cord
               from t in cord.DefaultIfEmpty()
             where t.price > 100
             select new {CustName = c.Name, OrderID = (t == null ? 0 : t.OrderId)};