我需要帮助在linq语句中执行左连接.我的T-sql查询按预期工作,但我似乎无法从Linq获得想要的结果.我也意识到像我这样的问题很多,但我似乎无法对我的案例应用任何解决方案.
产品表
+---+------------+-----------+
| |transportID | Type(int)|
+---+------------+-----------+
| 1 | 5 | 1 |
| 2 | 5 | 3 |
| 3 | 6 | 3 |
+---+------------+-----------+
Run Code Online (Sandbox Code Playgroud)
商店
+---+------------+-------------+
| |Name |Type1(string)|
+---+------------+-------------+
| 1 | Ho | 1 |
| 2 | He | 2 |
| 3 | Be | 3 |
| 4 | Ke | 4 |
| 5 | Fe | 5 |
+---+------------+-------------+
Run Code Online (Sandbox Code Playgroud)
我想要的结果是
+---+------------+-------------+
| |Type |Count |
+---+------------+-------------+
| 1 | 1 | 1 |
| 2 | 2 | 0 |
| 3 | 3 | 1 |
| 4 | 4 | 0 |
| 5 | 5 | 0 |
+---+------------+-------------+
Run Code Online (Sandbox Code Playgroud)
我的tsql按预期工作
SELECT
Type1,
Count(Pro.transportId) as Count
FROM dbo.stores as sto
left Join dbo.products as pro on (sto.Type1 = pro.Type AND pro.transportId=5)
Where Type1 is not null
group by Type1
ORDER BY Type1 * 1 ASC
Run Code Online (Sandbox Code Playgroud)
我的Linq尝试返回此.
+---+------------+-------------+
| |Type |Count |
+---+------------+-------------+
| 1 | 1 | 1 |
| 3 | 3 | 1 |
+---+------------+-------------+
Run Code Online (Sandbox Code Playgroud)
Linq声明.
var res = (from sto in _context.Stores
join pro in _context.Products on sto.Type1 equals System.Data.Objects.SqlClient.SqlFunctions.StringConvert((double)pro.Type).Trim()
where pro.transportId == transportId
group pro by pro.Type1 into pt1
select new TypeTransportation()
{
Type = pt1.Key, // Needs to be int
Count = pt1.Count()
}).ToList();
Run Code Online (Sandbox Code Playgroud)
我试过做一些defaultifempty但似乎无法使它工作.
以下是 MSDN 链接“如何:使用 LINQ 执行左外连接”: https: //msdn.microsoft.com/en-gb/library/bb397895.aspx
你的代码应该是这样的:
var res = (from sto in _context.Stores
join pro in _context.Products on sto.Type1 equals System.Data.Objects.SqlClient.SqlFunctions.StringConvert((double)pro.Type).Trim() into grpJoin
from product in grpJoin.DefaultIfEmpty()
where product.transportId == transportId
group product by product.Type1 into pt1
select new TypeTransportation()
{
Type = pt1.Key, // Needs to be int
Count = pt1.Count()
}).ToList();
Run Code Online (Sandbox Code Playgroud)