Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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


What I have tried:

I have tried installing LINQER but it doesn't install. Googling around won't give me another tool.... please help
Posted
Updated 11-Jan-17 7:34am
Comments
Wendelius 10-Jan-17 5:46am    
What kind of LINQ query you're after? Are you using Entity Framework and how? Please post an example of what you have tried.
Andy Lanng 10-Jan-17 6:19am    
have you tried linqpad? I hear good things but I have not tried it myself. At least, not it's current iteration.
Jon McKee 11-Jan-17 1:17am    
Could you explain what the SQL command is trying to accomplish? I'm particularly interested in "WHERE OrderID IN (SELECT OrderID FROM OrderDetails WHERE ProductID = 1) AND OrderDetails.ProductID <> 1." Is this SQL attempting to find ProductName/OrderDetails combinations that don't have the proper data? The LINQ isn't too hard but all mock-ups I attempt return nothing because of this statement. You filter by OrderID's that have ProductID = 1, but then subsequently filter on ProductID != 1. This seems counter-intuitive unless errors are expected.
Willie254 11-Jan-17 3:51am    
I am building an e-commerce site and the SQL (or rather the LINQ I need) is to implement the "Those who bought product A also bought B,C,D,E products". Hope this help you get the insight. I know it could be simple but am new to LINQ, please help.

1 solution

C#
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);


Still not really sure what the OrderID IN (SELECT ....) section accomplishes but you can do that with something like this:
C#
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.
 
Share this answer
 
Comments
Maciej Los 12-Jan-17 2:40am    
Good job!
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900