0

当使用 GridView 的内置排序与实体框架时,我可以显示外键值。例如...

<asp:boundfield HeaderText="Category" DataField="Category.Name" SortExpression="Category.Name" />

...但是当单击标题以对网格中的项目进行排序时,如何按 Category.Name 对列表列表进行排序?

我只有字符串“Category.Name”,所以我不能这样做:

.OrderBy( e => e.Category.Name )

所以我尝试了反射......

private static object GetPropertyValue( object obj, string propertyName )
{
    PropertyInfo propertyInfo = obj.GetType().GetProperty( propertyName );
    return propertyInfo.GetValue( obj, null );
}

// list is List<Widget>
// with a breakpoint here, ((Widget)list[i]).Companies.Name exists in all Widgets
list.OrderBy( e => GetPropertyValue( e, "Category.Name" ) )

...这是行不通的。没有抛出异常,但不按 Category.Name 排序。

有任何想法吗?

4

1 回答 1

3

过去几天我一直在尝试解决这个问题,因为我正在将现有的 ASP.NET 应用程序从使用 SqlDataSources 移动到 EntityDataSources。我发现你必须放置一个“它”。在声明的前面。

因此,以上面的示例为例,您需要像这样形成它:

<asp:boundfield HeaderText="Category" DataField="Category.Name" SortExpression="it.Category.Name" />

我有一个如下所示的实体数据源:

<asp:EntityDataSource runat="server" ID="edsResourceRoles"  ConnectionString="name=SkillsEntities"
    DefaultContainerName="SkillsEntities" EnableUpdate="true" EnableDelete="true"
    EnableInsert="true" EntitySetName="ResourceRoles" Where="it.resource_id = @resource_id"
    Include="Roles,Competency_Level" OrderBy="it.Roles.roles_nm">

然后我可以使用 SortExpression="it.Roles.roles_nm" 控制角色名称列的排序。

希望这可以帮助其他正在寻找答案的人。

于 2009-11-06T15:00:30.870 回答