我一直关注微软的walkthrough on how to use Entity Framework,但在尝试将查询的结果放入组合框时,我得到以下异常:
“无法转换类型的对象 'System.Data.Entity.Infrastructure.DbQuery`1 [SchoolEF.Department]'到 输入'System.Data.Entity.Core.Objects.ObjectQuery'。“
在stackoverflow上搜索后,我发现this回答了类似的问题,但我不知道如何使用我的程序上下文中给出的解决方案,因为Execute不在DbQuery
中我需要一个DbContext来访问数据库。
以下是相关代码,其中SchoolEntities扩展了DbContext,而departmentList是一个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);
}
答案 0 :(得分:1)
这应该有效:
//...
this.departmentList.DataSource =departmentQuery.ToList();
您无需执行该转换即可设置DataSource
。只需调用ToList
扩展方法即可实现查询结果。您还应该设置ValueMember
:
this.departmentList.ValueMember = "Id";// PK of department entity
答案 1 :(得分:0)
this.departmentList.DataSource = ((ObjectQuery)departmentQuery).Execute(MergeOption.AppendOnly);
this.departmentList.DataBind();
可能只是缺少dataBind instrction。我不知道你如何将数据源放在组合框中。