Linq to SQL error : An order by expression can only contain non-constant scalars

后端 未结 2 399
南笙
南笙 2020-12-18 14:46

I\'m using a GridView and a LinqDataSource to view the Categories table. I set the Gridview to enable sorting. Sorting generally works except when i clicked on the header of

2条回答
  •  执念已碎
    2020-12-18 15:38

    I've clicked on this question a dozen times and have finally found the answer for it. @neo answered it here.

    My example SQL before:

    SELECT * 
    FROM [tblRoom]
    WHERE [Building] = <%= bldgdbid %>
    AND [Floor] LIKE CAST('<%= flr %>' AS NVARCHAR(127))
    ORDER BY CAST([RoomName] AS NVARCHAR(255))
    

    which I turned into this LINQ query:

    (From zz In tblRooms
     Where zz.Building = bldgdbid
     Select zz
     ).Where(Function(x) Convert.ToString(x.Floor).ToLower() = flr.ToLower()
     ).OrderBy(Function(y) Convert.ToString(y.RoomName))
    

    which LINQPad generates:

    SELECT [t0].[DBID], [t0].[Building], [t0].[ID], [t0].[Floor], [t0].[RoomName]
    WHERE (LOWER(CONVERT(NVarChar(MAX),[t0].[Floor])) = @p0) AND ([t0].[Building] = @p1)
    ORDER BY CONVERT(NVarChar(MAX),[t0].[RoomName])
    

    so it uses CONVERT not CAST, but that's good enough for me! And, it should be good enough for you because CAST is ANSI and CONVERT is SQL Server specific, but more powerful.

    It looks sloppy as heck, but I'm moving to Entity Framework and all LINQ is easier.

提交回复
热议问题