2

Is it possible to do orderby expression using linq query expression based on dynamic string parameter? because the query i have is producing weird SQL query

my linq:

var product = from prod in _context.Products
              join cat in _context.Categories on prod.CategoryId equals cat.CategoryId
              join sup in _context.Suppliers on prod.SupplierId equals sup.SupplierId
              orderby sortParam
              select new ProductViewModel
              {
                   ProductName = prod.ProductName,
                   ProductId = prod.ProductId,
                   QuantityPerUnit = prod.QuantityPerUnit,
                   ReorderLevel = prod.ReorderLevel,
                   UnitsOnOrder = prod.UnitsOnOrder,
                   UnitPrice = prod.UnitPrice,
                   UnitsInStock = prod.UnitsInStock,
                   Discontinued = prod.Discontinued,
                   Category = cat.CategoryName,
                   Supplier = sup.CompanyName,
                   CategoryId = cat.CategoryId,
                   SupplierId = sup.SupplierId
              };

where var sortParam = "prod.ProductName"

The code above produces weird sql where order by sortParam is being converted to (SELECT 1). Full query catched by sql profiler below:

exec sp_executesql N'SELECT [prod].[ProductName], [prod].[ProductID], [prod].[QuantityPerUnit], [prod].[ReorderLevel], [prod].[UnitsOnOrder], [prod].[UnitPrice], [prod].[UnitsInStock], [prod].[Discontinued], [cat].[CategoryName] AS [Category], [sup].[CompanyName] AS [Supplier], [cat].[CategoryID], [sup].[SupplierID]
FROM [Products] AS [prod]
INNER JOIN [Categories] AS [cat] ON [prod].[CategoryID] = [cat].[CategoryID]
INNER JOIN [Suppliers] AS [sup] ON [prod].[SupplierID] = [sup].[SupplierID]
ORDER BY (SELECT 1)
OFFSET @__p_1 ROWS FETCH NEXT @__p_2 ROWS ONLY',N'@__p_1 int,@__p_2 int',@__p_1=0,@__p_2=10

I'm seeing a lot of people doing linq order by using dynamic parameter but all of them use lambda not query expression, please enlighten me

Fatikhan Gasimov
  • 763
  • 1
  • 11
  • 31
sprgdy
  • 81
  • 10
  • `sortParam` is a string variable with a constant value during the query, sorting by a constant value is the same as not sorting. – NetMage Mar 13 '19 at 18:55

1 Answers1

0

As was already mentioned, you are passing a string value instead of an expression that reflects the column name. There are options for what you want however, see for example here.

Jeroen V
  • 160
  • 6