Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery) is not supported

Am coding on visual studio 2012 and using Entity Model as my Data layer. However, my drop down control with the Linq statement tend to throw an unhandled exception when the page tries to load (stated title above). Here is my code below;

using (AdventureWorksEntities dw = new AdventureWorksEntities())
        {
            ddlCon.DataSource = (from em in dw.Employees
                                 select new { em.Title, em.EmployeeID });

            ddlCon.DataTextField = "Title";
            ddlCon.DataValueField = "EmployeeID";
            ddlCon.DataBind();
            ddlCon.Items.Insert(0, new ListItem("--Select--", "--Select--"));
        }
  1. I want to know why that error occurred
  2. What should be the proper way to bind to a control when using LINQ?
like image 964
Oluwafemi Avatar asked Oct 17 '12 15:10

Oluwafemi


2 Answers

The error is fairly clear - you can't bind directly to the query results, but need to populate some local collection instead.

The simplest way to do this is to convert it to a List<T>, via ToList():

 ddlCon.DataSource = (from em in dw.Employees
                             select new { em.Title, em.EmployeeID }).ToList();
like image 100
Reed Copsey Avatar answered Nov 14 '22 16:11

Reed Copsey


Or if you want to avoid writing a LINQ expression you could just do this:

var dbContext = new EF.CustomerEntities();
gvCustomers.DataSource = dbContext.CustomersTable.ToList();
like image 7
Denys Wessels Avatar answered Nov 14 '22 14:11

Denys Wessels