0

假设我在 1 到 1 或 0 关系上有 2 个表,如下所示:

Invoice: ID, Date, OrderID
Order:   ID, Date, Notes (string)

就 LINQtoSQL 而言,我的 INNER JOIN 为:

customer
.invoices
.OrderByDescending(i => i.Date)
.Join(context.Orders,
    invoice => invoice.OrderID,
    order => order.OrderID,
    (invoice, order) => new
    {
        invoice = invoice,
        OrderNotes = order.Notes
    })
.ToList()

在内连接中排除的所有值都是WHERE Invoice.OrderID NOT IN (SELECT OrderID FROM Order),我没有检查会发生什么WHERE Invoice.OrderID IS NULL

所需的查询是:

SELECT i.*, o.Notes AS OrderNotes 
FROM 
    Invoice AS i
LEFT OUTER JOIN 
    Order AS o
ON i.OrderID = o.OrderID

我知道应该切换 fk,但我无权更改数据库的结构。

我不知道如何产生 LEFT OUTER JOIN 效果。环顾四周,我只找到了 1 到多个 LEFT JOIN 的解决方案。

4

3 回答 3

1

msdn 上的优秀示例

http://msdn.microsoft.com/en-us/library/bb397895.aspx

应该是这样的

from i in invoice
join o in order on i.OrderID = o.OrderID into result
from r in result.DefaultIfEmpty()
select new {i.Id, i.someProperty , Notes = (r== null ? String.Empty : r.Notes) };
于 2012-05-29T10:01:51.833 回答
1

试试这个:

var query = from invoice in context.Invoices
                    join order in context.Orders on new { invoice.OrderId } equals new { order.Id } into groupedJoin
                    from grOrder in groupedJoin.DefaultIfEmpty()
                    select new { Invoice = invoice, Order = grOrder };
于 2012-05-29T10:10:42.273 回答
0

感谢所有的建议,我已经弄清楚了如何以基于方法的语法来做到这一点。

customer
.invoices
.OrderByDescending(i => i.Date)
.GroupJoin(context.Orders,
    invoice => invoice.OrderID,
    order => order.OrderID,
    (invoice, orders) => new
    {
        invoice = invoice,
        OrderNotes = orders.SingleOrDefault()==null?"":orders.SingleOrDefault().Notes
    })
.ToList()

关键是 GroupJoin 即使它看起来像一对多关系 JOIN 它的工作方式是 SQL

于 2012-05-30T01:55:20.213 回答