C# 不支持直接绑定到商店查询(DbSet、DbQuery、DbSqlQuery)的数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12938371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery) is not supported
提问by Oluwafemi
Am coding on visual studio 2012and using Entity Modelas 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;
我在Visual Studio 2012上编码并使用实体模型作为我的数据层。但是,当页面尝试加载时,我使用 Linq 语句的下拉控件往往会引发未处理的异常(上述标题)。下面是我的代码;
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--"));
}
- I want to know why that error occurred
- What should be the proper way to bind to a control when using LINQ?
- 我想知道为什么会发生那个错误
- 使用 LINQ 时绑定到控件的正确方法是什么?
采纳答案by Reed Copsey
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():
最简单的方法是将其转换为 a List<T>,通过ToList():
ddlCon.DataSource = (from em in dw.Employees
select new { em.Title, em.EmployeeID }).ToList();
回答by Denys Wessels
Or if you want to avoid writing a LINQ expression you could just do this:
或者,如果您想避免编写 LINQ 表达式,您可以这样做:
var dbContext = new EF.CustomerEntities();
gvCustomers.DataSource = dbContext.CustomersTable.ToList();
回答by Chameleon
though this question has already been answered still I want to show that you can even get the answer directly from the message box as well (i got the same error) ERROR DIALOGUE BOX IMAGE
虽然这个问题已经得到回答,但我想表明你甚至可以直接从消息框中得到答案(我也遇到了同样的错误)错误对话框 图像
using (var retrive=new Models.Academy_MSDBEntities())
{
var query = retrive.Students.Where(s => s.Year == year).ToList();
return query;
}

