I have many to many relationship, table Product, table Category and join table ProductCategory.
I need to convert this SQL query to LINQ C#:
Select TOP 3 Categories.id, Categories.Description, avg(Products.Price) as MeanPrice, count(Products.IsAvailable) as NumberOfAvailableProducts
FROM Categories
INNER JOIN ProductCategories on Categories.Id =
ProductCategories.CategoryId
INNER JOIN Products on Products.Id = ProductCategories.CategoryId
WHERE Products.IsAvailable='true'
GROUP BY Categories.Id, Categories.Description
ORDER BY MeanPrice DESC
I would appreciate help, thanks.
For translating SQL to LINQ query comprehension:
DISTINCT
,TOP
, etc) into functions applied to the whole LINQ query.new {
...}
) for multiple columns..DefaultIfEmpty()
.COALESCE
with the conditional operator and a null test.IN
to.Contains()
andNOT IN
to!
...Contains()
SELECT *
must be replaced with select range_variable or for joins, an anonymous object containing all the range variables.SELECT
fields must be replaced withselect new {
...}
creating an anonymous object with all the desired fields or expressions.FULL OUTER JOIN
must be handled with an extension method.There are so many examples in the Internet for you to start learning how to write LINQ effectively (including the post from NetMage above).
But I would give you the examples anyway, based on your case above, with an assumption that this T-SQL of yours :
might've been a typo, because what you really meant was maybe like this :
So, this is the snippet when you ask me how could I do that in LINQ :
So, that's it. I hope you can get something from my post here, and later may create your own, a better version of this quick example.
Good luck!