如何使用 linq/Entity Framework 绑定 gridview?
我需要绑定 GridView,我正在使用此代码:
ProductDBEntities db = new ProductPDBEntities();
var pro = from u in db.Products where u.PID == 1 select u;
if (pro != null)
{
GridView1.DataSource = pro;
GridView1.DataBind();
}
并收到此错误。
系统.InvalidOperationException: 序列包含多个 元素
可以告诉我我做错了什么吗?
I need to bind GridView
, I am using this code:
ProductDBEntities db = new ProductPDBEntities();
var pro = from u in db.Products where u.PID == 1 select u;
if (pro != null)
{
GridView1.DataSource = pro;
GridView1.DataBind();
}
and getting this error.
System.InvalidOperationException:
Sequence contains more than one
element
Can somebody please tell me what am I doin wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
检查
重复
,然后尝试绑定它。我编辑了我的最后一个答案以显示完整的代码:
Check
Duplication
and then try to bind it.I have edited my last answer in order to display the complete code :
此代码可能会有所帮助:
如果您有一张表并且表详细信息可以使用此代码:
This code may be helpful:
If you have a table and table detail can use this one:
首先,您可以检查数据以查看是否有多个 PID = 1 的产品。
其次,您可以使用 .First() 方法来确保只获得一个绑定结果:
First, you might check your data to see if there's more than one product with PID = 1.
Second, you can use the .First() method to make sure you get only one result for binding:
将变量存储为对象类型并将对象类型作为数据源分配给网格
Store the variable to object type and assign the object type as datasource to grid
我认为你必须在添加到
DataSource
时执行ToList()
:注意:由于它是一个
GridView
,因此必须采取n个数量行。无行数限制
。I think you have to do
ToList()
when to add toDataSource
:Note: As it is a
GridView
, has to take n number of rows.No row limit
.我这样解决:
我尝试一下。这是工作。
I solve like this:
I try it. It's work.