需要帮助将SQL代码转换为LINQ [英] Need help converting SQL code to LINQ
问题描述
有人可以帮我转换下面的SQL到LINQ,我已经尝试了所有徒劳无功的LINQ代码。
Can someone please help me convert the following SQL to LINQ, I have tried all in vain to get a LINQ code that would work.
SELECT TOP 5 ProductName, COUNT(ProductName) AS CountOfProducts FROM OrderDetails
INNER JOIN Products ON OrderDetails.ProductID = Products.ProductID
WHERE OrderID IN (
SELECT OrderID FROM OrderDetails WHERE ProductID = 1
)
AND OrderDetails.ProductID <> 1
GROUP BY ProductName ORDER BY CountOfProducts DESC
我尝试过:
我已经尝试安装LINQER但它没有安装。谷歌搜索不会给我另一个工具....请帮助
What I have tried:
I have tried installing LINQER but it doesn't install. Googling around won't give me another tool.... please help
推荐答案
var query = (from order in db.OrderDetails
where order.ProductID != 1
join product in db.Products on order.ProductID equals product.ProductID
group product by product.ProductName into result
let count = result.Count()
orderby count descending
select new { ProductName = result.Key, CountOfProducts = count }
).Take(5);
仍然不太确定 OrderID IN(SELECT ....)
部分完成了什么,但你可以用这样的东西做到这一点:
Still not really sure what the OrderID IN (SELECT ....)
section accomplishes but you can do that with something like this:
db.OrderDetails.Any(o => o.ProductID == 1 && o.OrderID == external.OrderID)
我会把它留给你,因为我真的不能让查询在包含那个检查时做任何有用的事情。显然我在这里错过了一些关系。
I'll leave that up to you since I honestly can't get the query to do anything useful when including that check. Obviously I'm missing some relationship here.
这篇关于需要帮助将SQL代码转换为LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!