Using collation in Linq to Sql

后端 未结 2 656
谎友^
谎友^ 2020-12-03 20:06

Imagine this sql query

select * from products order by name collate Persian_100_CI_AI asc

Now using Linq:

product = DB.Prod         


        
2条回答
  •  感情败类
    2020-12-03 20:59

    You can't change the collation through a LINQ statement. You better do the sorting in memory by applying a StringComparer that is initialized with the correct culture (at least... I hope it's correct) and ignores case (true).

    DB.Products.AsEnumerable()
      .OrderBy (x => x, StringComparer.Create(new CultureInfo("fa-IR"), true))
    

    edit

    Since people (understandably) don't seem to read comments let me add that this is answered using the exact code of the question, in which there is no Where or Select. Of course I'm aware of the possibly huge data overhead when doing something like...

    DB.Products.AsEnumerable().Where(...).Select(...).OrderBy(...)
    

    ...which first pulls the entire table contents into memory and then does the filtering and projection the database itself could have done by moving AsEnumerable():

    DB.Products.Where(...).Select(...).AsEnumerable().OrderBy(...)
    

    The point is that if the database doesn't support ordering by some desired character set/collation the only option using EF's DbSet is to do the ordering in memory.

    The alternative is to run a SQL query having an ORDER BY with explicit collation. If paging is used, this is the only option.

提交回复
热议问题