Showing posts tagged iqueryable

Using the ASP.Net GridView with ObjectDataSource and IQueryable objects

I recently started to move a project from using ADO.Net Typed DataSets to the more “efficient and flexible” Entity Framework or more specifically ”LINQ to Entities”.

One of the first issues I ran into was the automatic Sorting and Paging that comes with binding GridViews to DataSets. Since I needed to change my data objects  from Datasets to IQueryable I was not happy about having to re-work how that was working. That’s where the fun began.

I first came across an article by Scott Guthrie Using the LINQ Dynamic Query Library and my initial thoughts where that is was way to complex for my needs. Considering I haven’t used LINQ to Entities extensively I was a little reluctant to dig in.

So after finally realizing how simple these extension methods for LINQ really are, I decided to prove out this would work well with my application. …here’s basically what I did.

Only requirements:
1. include the Dynamic.cs file in your project so you can use Scott’s LINQ extension methods.
2. create an Entity DB model called “Model1” and create a table called “People”.

 // Here’s the markup:
 <asp:GridView ID=”GridView1” runat=”server” DataSourceID=”odsTest” AllowPaging=”true” AllowSorting=”true”>
</asp:GridView>

<asp:ObjectDataSource ID=”odsTest” runat=”server” SelectMethod=”GetPeople” TypeName=”BLL” SortParameterName=”sortExpr” SelectCountMethod=”SelectPeopleCount” EnablePaging=”true”> </asp:ObjectDataSource>

 // Here’s The CodeBehind in C#:
// be sure to include “using System.Linq.Dynamic;” and make namespace “BLL”

public Model1Entities db = new Model1Entities();

public IQueryable GetPeople(string sortExpr, int maximumRows, int startRowIndex)
{
  var docs = from p in db.People
                 select p; 

   if (string.IsNullOrEmpty(sortExpr))
   {
      return docs.Skip(startRowIndex).Take(maximumRows);
   }
   else
   {
      var sortedDocs = docs.OrderBy(sortExpr).Skip(startRowIndex).Take(maximumRows);
       return sortedDocs; 
    }

    public int SelectPeopleCount()
    {
       return db.People.Count();
     }

}

After proving out the solution I came up with, I think my new DAL will definitely be much easier and more efficient to work with than those clunky Typed DataSets.  Cheers! 

Fork me on GitHub