Ruslan_K
Ruslan_K

Reputation: 423

Grid.Mvc + Entity Framework exception

Need help with Grid.Mvc. I'm passing IQueryable collection produced by Entity Framework and get exception

Action method:

public ActionResult Index(int id)
{
        IQueryable<Document> documents = _dbContext.Document;

        var model = new DocumentListViewModel()
        {                Documents = documents
        };

        return View(model);
}

DocumentListViewModel:

public class DocumentListViewModel
{
    public IQueryable<Document> Documents { get; set; }
}

View:

@model CompanyName.DocFlow.Web2.Models.DocumentListViewModel
@using GridMvc.Html;

@Html.Grid(Model.Documents).Columns(columns =>
                {
                    columns.Add(x => x.CreatedDate).Titled("Дата");//.Filterable(true);
                    columns.Add(x => x.IncomingNumber).Titled("Входящий номер");//.Filterable(true);
                    columns.Add(x => x.Description).Titled("Краткое описание");
                }).WithPaging(10)

Exception:

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.

The documentation states:

If your data source is database (for example) you need to pass IQueryable collection to the grid. Grid.Mvc uses IQueryable interface to construct query expressions to your data collection.

When you go to some page the grid invokes .Skip(N).Take(N) methods and when you sort data the grid invokes OrderBy or OrderByDescending methods etc.

Tutorial link: Grid.Mvc

Upvotes: 0

Views: 557

Answers (1)

MVC Grid Description :

When you go to some page the grid invokes .Skip(N).Take(N) methods and when you sort data the grid invokes OrderBy or OrderByDescending methods etc.

You can do the sorting process encapsulate field get method or you can do this same operation in ActionResult method

Sample Code :

public class DocumentListViewModel
{
    private IQueryable<Document> _Documents;
    public  IQueryable<Document> Documents 
   { 
     get 
     { 
        return _Documents.Ordery(x=>x.Id);
     } 
     set 
     { 
        _Documnets = value;
     } 
   }
}

or

public ActionResult Index(int id)
{
        IQueryable<Document> documents = _dbContext.Document.OrderBy(x=>x.Id);

        var model = new DocumentListViewModel()
        {             
            Documents = documents
        };

        return View(model);
}

Upvotes: 2

Related Questions