Friso
Friso

Reputation: 2428

How can I put a DbQuery's results into a ComboBox?

I've been following Microsoft's walkthrough on how to use Entity Framework, but I get the following exception when trying to put a query's results into a combobox:

"Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[SchoolEF.Department]' to type 'System.Data.Entity.Core.Objects.ObjectQuery'."

After searching on stackoverflow I found this answer to a similar problem, but I don't know how to use the solutions given in the context of my program since Execute isn't in DbQuery and I need a DbContext to access the database.

Below is the concerning code, where SchoolEntities extends DbContext and departmentList is a ComboBox.

private void CourseViewer_Load(object sender, EventArgs e)
        {
            schoolContext = new SchoolEntities();

            var departmentQuery = from d in schoolContext.Departments.Include("Courses")
                                  orderby d.Name
                                  select d;

            this.departmentList.DisplayMember = "Name";
            this.departmentList.DataSource = ((ObjectQuery)departmentQuery).Execute(MergeOption.AppendOnly);
        }

Upvotes: 1

Views: 109

Answers (2)

ocuenca
ocuenca

Reputation: 39326

This should work:

 //...
 this.departmentList.DataSource =departmentQuery.ToList();

You don't need to do that cast to set the DataSource. Just call ToList extension method to materialize the result of your query. Also you should set ValueMember:

this.departmentList.ValueMember = "Id";// PK of department entity

Upvotes: 1

Antoine Pelletier
Antoine Pelletier

Reputation: 3316

this.departmentList.DataSource = ((ObjectQuery)departmentQuery).Execute(MergeOption.AppendOnly);
this.departmentList.DataBind();

Probably just lacking the dataBind instrction. I don't know how you put your data source in your combo box though.

Upvotes: 0

Related Questions