How to sort with a CASE statement in an EntityDataSource?

懵懂的女人 提交于 2019-12-21 21:32:59

问题


I'm using a CASE statement in my EntityDataSource to do custom sorting. Consider the following code:

<asp:EntityDataSource ID="myEntityDataSource" runat="server" 
    ConnectionString="name=MySQLEntities1" 
    DefaultContainerName="MySQLEntities1" 
    EnableFlattening="False" 
    EntitySetName="Persons" 
    EntityTypeFilter="Persons"
    OrderBy="it.[Pack], 
             CASE it.[Type] 
                WHEN 'MAN' THEN 1 
                WHEN 'VROUW' THEN 2 
                WHEN 'KIND' THEN 3 
             END, 
             it.[BirthDate] ASC" />

In T-SQL this would be a perfecty normal way of sorting, but used in the EntityDataSource it throws the following exception:

The query syntax is not valid. Near identifier 'it', line 11, column 21.

How can I get this type of sorting to work in my EntityDataSource?


回答1:


I was trying the very same thing today. I discovered on the Entity SQL Reference site that you apparently have to use CASE WHEN and cannot use CASE [value] WHEN. This approach, although not as it would be in T-SQL, did work for me. So your code should look like this:

<asp:EntityDataSource ID="myEntityDataSource" runat="server" 
ConnectionString="name=MySQLEntities1"      
DefaultContainerName="MySQLEntities1"      
EnableFlattening="False"      
EntitySetName="Persons"      
EntityTypeFilter="Persons"     
OrderBy="it.[Pack],               
CASE 
WHEN it.[Type] = 'MAN' THEN 1                  
WHEN it.[Type] = 'VROUW' THEN 2                  
WHEN it.[Type] = 'KIND' THEN 3 END, it.[BirthDate] ASC" />

MSDN Entity SQL Reference: 'CASE'



来源:https://stackoverflow.com/questions/8279571/how-to-sort-with-a-case-statement-in-an-entitydatasource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!