Linq Full Outer Join错误

时间:2017-02-01 09:12:07

标签: c# linq linqpad

我使用Linqpad连接到Adventure Works 2012数据库,如下所示:

enter image description here

我正在尝试编写一个完整的外连接。我的研究告诉我它应该是这样的(如屏幕截图所示):

var LeftOuterJoin =  from p in Products
join pv in ProductVendors on p.ProductID equals pv.ProductID into ppv
from pv in ppv.DefaultIfEmpty()
select new {ProductName = p.Name};

var RightOuterJoin =  from v in Vendors
join pv in ProductVendors on v.BusinessEntityID equals pv.BusinessEntityID into ppv
from pv in ppv.DefaultIfEmpty()
select new {VendorName = v.Name};

LeftOuterJoin.Union(RightOuterJoin);

但是,屏幕截图中的错误(见截图)是:

'System.Linq.IQueryable<AnonymousType#1>' does not contain a definition for 'Union' and the best extension method overload 'System.Linq.ParallelEnumerable.Union<TSource>(System.Linq.ParallelQuery<TSource>, System.Collections.Generic.IEnumerable<TSource>)' has some invalid arguments

Instance argument: cannot convert from 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Linq.ParallelQuery<AnonymousType#2>'

有什么问题?

1 个答案:

答案 0 :(得分:2)

正如我所看到的,存在类型问题,匿名类型都有不同的属性,因此会导致使用Union的问题。您可以创建具有相同属性的公共类型并使用它。或根据查询同时具有属性和用途:

var LeftOuterJoin =  from p in Products
join pv in ProductVendors on p.ProductID equals pv.ProductID into ppv
from pv in ppv.DefaultIfEmpty()
select new {VendorName = "",
            ProductName = p.Name,};

var RightOuterJoin =  from v in Vendors
join pv in ProductVendors on v.BusinessEntityID equals pv.BusinessEntityID into ppv
from pv in ppv.DefaultIfEmpty()
select new {VendorName = v.Name,
            ProductName = "",};

var result = LeftOuterJoin.Union(RightOuterJoin).ToList(); // force execution to get results.

如果您使用LinqPad

,请使用此选项
var result = LeftOuterJoin.Union(RightOuterJoin)
result .Dump();

这对你有用。