views:

520

answers:

2

When using GridView's built in Sorting with Entity Framework, I can display foreign key values. For example...

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

...but when the header is clicked to sort the items in the grid, how can I sort my List list by Category.Name?

I only have the string "Category.Name", so I can't do this:

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

So I tried Reflection...

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" ) )

...which does not work. No exception thrown, but doesn't sort by Category.Name.

Any ideas?

A: 

I have been trying to figure this out for the last couple of days as i am moving an existing ASP.NET application from using SqlDataSources to EntityDataSources. I found that you have to place an "it." in front of the statement.

So taking your example above you would need to form it like this:

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

I have an Entity data source that looks like this:

<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">

and then i can control the sorting of the Roles Name column by using the SortExpression="it.Roles.roles_nm".

Hope this helps someone else out there who is looking for an answer.

Kyle
A: 

Thanks,it helped me after I got crazy :),because I don't know why for the another fields that is not foreign column I just put the field name without "it." in the sort expression and it works fine but for foreign key feilds,it must have "it." before the feild name..it is really misleading.

Anyway Thanks again

Marwa