Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc razor foreach in view with sorted data

I'm new to MVC.

I want to implement data sorting on my html page. I have a model that generated with this code:

public IEnumerable<PercConfigEntry> GetPercConfigEntries() 
{
    var results = from g in this.context.PercConfigEntry
                  where g.Key == "ConfigEntries"
                  select g;
    return results;
}

And a view:

@model IEnumerable<PercConfigEntry>
@foreach ( var config in Model )
{
   ...
}

This works. But when I add "orderby" to query like this:

public IEnumerable<PercConfigEntry> GetPercConfigEntries() 
{
    var results = from g in this.context.PercConfigEntry
                  where g.Key == "ConfigEntries"
                  orderby g.ConfigName
                  select g;
    return results;
}

it throws DataServiceQueryException on foreach.

What's wrong?

Thanks in advance.

like image 923
Max Avatar asked Nov 02 '22 17:11

Max


1 Answers

The problem has something do with your query provider; perhaps it simply doesn't support ordering. Without any further information, I'd recommend this:

public IEnumerable<PercConfigEntry> GetPercConfigEntries() 
{
    var results = 
        (from g in this.context.PercConfigEntry
         where g.Key == "ConfigEntries"
         select g)
        .AsEnumerable()
        .OrderBy(g => g.ConfigName);
    return results;
}

Or in fluent syntax:

public IEnumerable<PercConfigEntry> GetPercConfigEntries() 
{
    var results = this.context.PercConfigEntry
        .Where(g => g.Key == "ConfigEntries")
        .AsEnumerable()
        .OrderBy(g => g.ConfigName);
    return results;
}

This forces the query to be executed on the provider without any ordering, then re-orders it on the client—in other words, the call to AsEnumerable effectively disconnects the result set from the query provider so that the OrderBy (or any subsequent methods) are evaluated on the client. This is probably not as efficient as allowing the provider to order it, but if the provider is doesn't support ordering, this is the only way to do it.

like image 67
p.s.w.g Avatar answered Nov 15 '22 05:11

p.s.w.g