简体   繁体   English

SQL查询转换为LINQ左外部联接(VB.NET)

[英]SQL Query Conversion to LINQ Left Outer Join (VB.NET)

I've looked all around and spent way to long trying to convert this SQL statement into a Linq statement in VB. 我四处张望,花了很长时间尝试将SQL语句转换为VB中的Linq语句。 I'm sure it would be a good example for others out there - the statement is trying to pull products that have a many-to-many relationship with product categories, and the categories have a hierarchy of parents/children. 我敢肯定,这对于其他人来说将是一个很好的例子-该声明正试图拉出与产品类别具有多对多关系的产品,并且这些类别具有父级/子级的层次结构。

Here is the query I am trying to convert: 这是我要转换的查询:

SELECT  P.ProductID, P.ProductName, P.ProductSlug, P.PartNumber 
FROM         Products AS P 
INNER JOIN Products_Categories AS PC ON PC.ProductID = P.ProductID 
INNER JOIN Categories AS C ON PC.CategoryID = C.CategoryID 
LEFT OUTER JOIN Categories AS P_Cats ON P_Cats.CategoryID = C.Parent
WHERE     (C.CategoryID = 9) OR (C.Parent = 9) OR (P_Cats.Parent = 9)

I can get up to the point where I am trying to say "WHERE ... (P_Cats.Parent = 9)" but can't figure that part out. 我可以说到“ WHERE ...(P_Cats.Parent = 9)”,但无法弄清楚那部分。

THANKS! 谢谢!

Figured it out right after posting the question, but here is the answer in case anyone else finds it helpful: 在发布问题后立即找到答案,但是如果有人发现它有帮助,这里是答案:

Dim query = (From products In db.Products _
                Join PC In db.Products_Categories On PC.ProductID Equals products.ProductID _
                Join C In db.Categories On PC.CategoryID Equals C.CategoryID _
                Group Join cat In db.Categories On cat.CategoryID Equals C.Parent Into C_Parents = Group _
                From cParents In C_Parents.DefaultIfEmpty() _
                Where (C.CategoryID = categoryID Or C.Parent = categoryID Or cParents.CategoryID = categoryID) _
                And products.IsDeleted = False)

It was the line "From cParents In C_Parents.DefaultIfEmpty()" that I was leaving out. 我遗漏的是“来自C_Parents.DefaultIfEmpty()中的cParents”行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM