In this example here, Scott shows doing a Linq query against the dbContext and binding the result directly to a GridView to show a list of products. His example is using the CTP4 version of the Code First stuff.
However, when I try do do the same thing using the latest version of EntityFramework 4.1, I get the following error:
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.
I see that the DBQuery object is throwing this error on purpose in its implementation of IListSource.GetList(), which is used in databinding.
Any ideas why his example works? By the way, I know that I can make this work by putting in a projects.ToList()
. My main question is whether something changed in the release version that makes this type of thing no longer work, or whether I'm missing something somewhere that can work around this error.
Just for reference, I'm referring to code like this:
MyDbContext db = new MyDbContext();
var projects = from p in db.Projects
where p.AnotherField == 2
select p;
grdTest.DataSource = projects;
grdTest.DataBind();
ToList
anyway because context is disposable and you want to dispose it once you don't need it. Many times this happens before the page is rendered (and query executed => exception).ToList
will ensure that your query is executed when the context exists. – Stephi