0

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!

Gal Ziv
  • 6,890
  • 10
  • 32
  • 43

2 Answers2

1

Try this:

get { return this.RequestStatuses.ToList().Last().Status; }

or

get { return this.RequestStatuses.OrderByDescending(ee=>ee.YourPropery).First().Status; }

And read this

LINQ To Entities does not recognize the method Last. Really?

Community
  • 1
  • 1
George Vovos
  • 7,563
  • 2
  • 22
  • 45
  • that doesnt work. it won't work if i have a simple field which is not mapped to entity. for example: public string SomeProp { get; set;}. gives the same error. – Gal Ziv Aug 11 '14 at 06:08
0

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

Gal Ziv
  • 6,890
  • 10
  • 32
  • 43