Tuesday, January 14, 2014

Data binding to an ASP.NET GridView control using LINQ and Entity Framework DbContext

I have been using Entity Framework for quite a few years and when I first started using Entity Framework, the only option was using traditional ObjectContext.

However, with the more recent releases of Entity Framework, the recommendation is to now use DbContext in favor of ObjectContext

Therefore, I began updating all of my Entity Framework Class Libraries over to the new DbContext, but after compiling my solution and attempting to use a LINQ Query to bind to an ASP.NET GridView, I received the following error message:

Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery) is not supported. Instead populate a DbSet with data, for example by calling Load on the DbSet, and then bind to local data. For WPF bind to DbSet.Local. For WinForms bind to DbSet.Local.ToBindingList().

After doing some research on the web as to the nature of this error message, I discovered, that I simply had to cast my LINQ Query to a List (by appending .ToList() to the end of the LINQ Query result).

Once I did that, I was able to successfully bind my LINQ Query to the GridView control without receiving any further error messages!!

No comments:

Post a Comment