Employee_ID int
Employee_Name varchar(50)
Sales_ID int
Employee_ID int
Sale_Amount money
选择
*
从
员工人数
左外连接
销售人员
在
s.Employee_ID = emp.Employee_ID
1 Emp1 1 1 150.00
1 Emp1 2 1 500.00
2 Emp2 3 2 250.00
3 Emp3 NULL NULL NULL
4 Emp4 NULL NULL NULL
5 Emp5 4 5 700.00
Dim query = From emp In entiites.Employee _
From sales In emp.Sales _
Select _
emp, _
sales
1:Emp1:150.0000
1:Emp1:500.0000
2:Emp2:250.0000
5:Emp5:700.0000
Dim query = From emp In entiites.Employee _
Group Join sales In entiites.Sales _
On emp.Employee_ID Equals sales.Employee.Employee_ID _
Into sales_grp = Group _
From Sel_SalesGrp In sales_grp.DefaultIfEmpty() _
Select _
emp, _
Sel_SalesGrp
然后我使用DefaultIfEmpty收到此错误:
LINQ to Entities无法识别方法'System.Collections.Generic.IEnumerable 1[m12Model.Sales] DefaultIfEmpty[Sales](System.Collections.Generic.IEnumerable
1 [m12Model.Sales])'方法,并且此方法无法转换为商店表达式。
答案 0 :(得分:2)
您需要使用“Into”和“DefaultIfEmpty()”关键字执行左连接:
Dim query = From emp In entities.Employee _
Join sal In entities.Sales On emp.Employee_ID Equals sal.Employee_ID Into LeftJoinSal _
From ljs In LeftJoinSal.DefaultIfEmpty() _
Select _
emp, _
ljs
此网站显示了另一个简单示例:GeeksWithBlogs。虽然它在C#中。
关键是你需要加入一个新名称,以防止它过滤你的第一个表(隐藏不加入的行)的结果,然后使用DefaultIfEmpty()函数从中选择,在没有连接的情况下提供默认值(null)。
答案 1 :(得分:0)
这个怎么样:
Dim query = From emp In entiites.Employee Join sales In In entiites.Sales _
On emp.Employee_ID Equals sales.Employee_ID select new { emp, sales }
您可以选择所需的列,而不是“选择新的{emp,sales}”。这应该是使用LINQ的标准左连接。
答案 2 :(得分:0)
你现在可能已经找到了解决方案,但我有一个建议,使用与连接不同的方法:
Dim db As New TestEntities
Dim EmptySale As Decimal? = Nothing
Dim Q = (From emp In db.Employee From sale In emp.Sale _
Select emp.Name, amount =sale.SaleAmount).ToList
Dim Q2 = (From emp In db.Employee Where Not emp.Sale.Any _
Select emp.Name, amount = EmptySale)
Dim Q3 = From emp In Q.Union(Q2) Order By emp.Name, emp.amount
For Each e In Q3
Console.WriteLine("{0} {1}", e.Name, e.amount)
Next
结果是:
Emp1 150,00
Emp1 500,00
Emp2 250,00
Emp3
Emp4
Emp5 750,00
我希望这可以帮到你