得到一个错误“不支持”.用户代码“未处理”异常
本文关键字:未处理 不支持 代码 异常 用户 错误 一个 | 更新日期: 2023-09-27 18:05:56
我有一个表
product(table name)
product_id
product_name
product_image
product_price
product_description
category_id
category(table name )
category_id
category_name
category_description
我有一个命名为categoryCombobox
的组合框和命名为productgridview
的网格视图
我试图根据组合框中的选择填充数据网格。像这样....
private viod form_load(object sender, EventArgs e)
{
var products = from prods in abc.products
select new
{
prods.product_Id,
productname = prods.product_Name,
productimage = prods.product_Image,
productprice = prods.product_Price,
productdescription = prods.product_Description
};
productbindingsource.DataSource = products;
productgridview.DataSource = productbindingsource;
productgridview.Columns[0].Visible = false;
}
private void categoryCombobox_SelectedIndexChanged(object sender, EventArgs e)
{
// is this query correct
var categoryid = from productcategories in abc.categories
where productcategories.category_Name.Equals(categoryCombobox.Text)
select productcategories.category_Id;
var produc = from pros in abc.products
where pros.Category_Id.Equals(categoryid)
select new
{
productname = pros.product_Name,
productimage = pros.product_Image,
productprice = pros.product_Price,
productdescription = pros.product_Description
};
productbindingsource.DataSource = produc;
productgridview.DataSource = productbindingsource;
productgridview.Columns[0].Visible = false;
}
出现如下错误......
错误:在这一行productindingsource。数据源= product;
用户代码未处理不支持的异常
不能比较'System.Linq.IQueryable ' 1'类型的元素。只有基本类型(如Int32、String和Guid)和实体支持的类型
var categoryid = from productcategories in abc.categories
where productcategories.
category_Name.Equals(categoryCombobox.Text)
select productcategories.category_Id;
在调试时悬停在var
上。您将看到它不是您所期望的id,而是IEnumerable
。你要做的是
// .First() trips the query and returns a single category_Id
var id = (from productcategories in abc.categories
where productcategories.
category_Name.Equals(categoryCombobox.Text)
select productcategories.category_Id).First();
var produc = from pros in abc.products
where pros.Category_Id.Equals(id)
select new
{
productname = pros.product_Name,
productimage = pros.product_Image,
productprice = pros.product_Price,
productdescription = pros.product_Description
};
注意ids.First()
,它获取初始查询的第一个结果。
您正在尝试将int字段与可枚举集进行比较。
如果categoryID查询只返回一个值,那么试试这个:
var produc = from pros in abc.products
where pros.Category_Id.Equals(categoryid.Single())
select new
{
productname = pros.product_Name,
productimage = pros.product_Image,
productprice = pros.product_Price,
productdescription = pros.product_Description
};
如果它应该返回一个id列表,您将需要编写一个带有连接的单个查询。我假设它应该是单基于名称categoryId
edit -可能不是100%语法正确
var produc = from pros in abc.products
join cats in abc.categories on cats.category_id equals pros.Category_Id
where cats.category_Name.Equals(categoryCombobox.Text)
select new
{
productname = pros.product_Name,
productimage = pros.product_Image,
productprice = pros.product_Price,
productdescription = pros.product_Description
};