Model binding has a lot of benefits and saves a lot of time when you want to throw some data into a gridview on a page and get it up and running quickly. For example, I can have this Employee class
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Job> Jobs { get; set; }
[NotMapped]
public Job CurrentJob
{
get { return Jobs.OrderByDescending(x => x.StartDate).FirstOrDefault(); }
}
I throw this into a gridview using Model Binding and a template field for the calculated property:
<asp:GridView runat="server" id="gvDataItemType" ItemType="Model.Employee" SelectMethod="Select" AllowSorting="True">
<Columns>
<asp:DynamicField DataField="Name"/>
<asp:DynamicField DataField="Email"/>
<asp:TemplateField HeaderText="Job" SortExpression="???">
<ItemTemplate>
<asp:Label ID="lblJobTitle" Text='<%# Bind("CurrentJob.JobName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
...
with the following Select Method in code behind:
public IQueryable<Employee> Select()
{
MyContext context = new MyContext();
return context.Employees;
}
Everything sorts wonderfully except, obviously, the CurrentJob.JobName property.
My question is: How can I sort the GridView on the CurrentJob.JobName property?