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

后端 未结 2 373
南笙
南笙 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:28

    SQL Server just doesn't let you order by NText fields (see also error 420 in the SQL Server Error List). My guess is that it's for efficiency reasons, but I couldn't say for sure.

    Now the solution in the linked article is cast to nvarchar... but that's obviously pretty hard to do in LINQ.

    Does your description field definitely need to be an ntext?

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题