LINQtoSQL LEFT JOIN以1对1关系,基于方法

时间:2012-05-29 09:55:43

标签: c# linq-to-sql lambda entity-framework-4.1

假设我在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的解决方案。

3 个答案:

答案 0 :(得分: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) };

答案 1 :(得分: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 };

答案 2 :(得分: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即使它看起来像1对多关系JOIN它的方式是SQL