Search code examples
c#asp.net-mvcentity-frameworkwebgrid

MVC WebGrid of complex type


Im creating a webgrid. one of my column is of collection complex type:

[Table("RequestStatus",Schema="dbo")]
public class RequestStatus
{
    [Key]
    public int Id { get; set; }

    public string Status { get; set; }
}

and in my entity:

    public virtual ICollection<RequestStatus> RequestStatuses { get; set; }

in my webgrid i want to be able to sort by this property in a way similar to this:

   RequestStatuses.Last().Status

I created a readonly property in my entity:

    [NotMapped]
    public string LastRequestStatus
    {
        get { return this.RequestStatuses.Last().Status; }
    }

but i get:

System.NotSupportedException: The specified type member 'LastRequestStatus' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supporte

I assume that is becasue this property is not mapped to db field. is there a way to handle this situation out of the box or i need to write custom sorting for that?

Thanks in advance!


Solution

  • I created a some kind of custom sorting. when I issue in query string sort={propery which doesn't exist} webgrid doesnt do the sort but gives the result as is. if I edit the header of this column to issue a query string with the _LastRequestStatus (in my case), I check in controller if querystring["sort"] equals to this string (_LastRequestStatus) , do the appropriate sort (ASC,DESC - sortdir in querystring), and pass that list to the view as I did before. from there webgrid handles the paging as desired without intervention. All can be done in view+controller without the need for client-side script (which generally i have no problem with but i think this way it is more readable, especially if i see this code in a few months).