Left Outer Join ObjectSet <t>到IQueryable

时间:2015-07-31 03:32:35

标签: c# linq entity-framework outer-join

我尝试在多个DbContext.Set上执行左外连接和内连接,但内连接会阻止外连接正常工作。我的桌子:

供应商:

ID, Name
V1, Alan
V2, Brad
V3, Cath

地区:

ID, Name
R1, Ohio
R2, Utah
R3, Iowa

订单:

ID, VendorID, RegionID
O1,       V1,       R1
O2,       V1,       R2
O3,       V2,       R1
O4,       V2,       R3
O5,       V3,       R2
O6,       V3,       R3

我想运行一个查询,如果它们没有任何空白值,则返回按地区显示订单的所有供应商。因此,如果我想使用爱荷华州作为区域运行查询,结果将是:

Vendor, OrderID
Alan,   
Brad,  O4
Cath,  O5

在sql中,我会使用where value = 'bar' or value is null语法或使用内部联接创建临时表,然后外部连接临时表和外部联接表。我如何在linq中执行此操作?我似乎无法使用&#39; ...或者是null&#39;而且我无法加入一个Set和一个IQueryable(这是我从查询中创建&#39;临时表时得到的。

这是我目前根据多个googe搜索并查看SO的尝试:

var orders = from o in context.Orders
            where o.RegionID == region.ID  // region is an object from the EF model 'Region' class
            select o;

var vendorOrders = from v in context.Vendors
                   where vendorNameList.Contains(v.Name) // vendorNameList is a string []
                   join orders on v equals orders.Vendor into list
                   from vo in list.DefaultIfEmpty()
                   select new { Vendor = v, Order = orders == null ? "" : orders.ID };

这不用&#39;编译是一个变量,但用作类型&#39;在&#34;加入订单v等于orders.Vendor到列表&#34;线。

如何让所有供应商参与我的结果?

2 个答案:

答案 0 :(得分:1)

尝试此代码先生

var vendorOrders = from v in context.Vendors
                   where vendorNameList.Contains(v.Name) // vendorNameList is a string []
                   join v1 in orders.toList() on v equals v1.Vendor into list
                   from vo in list.DefaultIfEmpty()
                   select new { Vendor = v, Order = orders == null ? "" : orders.ID };

答案 1 :(得分:0)

尝试此查询

var vendorOrders = from v in context.Vendors.where(x=>vendorNameList.Contains(x.Name)) // vendorNameList is a string []
from o in context.Orders.where(x=>x.RegionID == region.ID && x. VendorID==v. ID).DefaultIfEmpty()
                   select new { Vendor = v, Order = orders == null ? "" : orders.ID };