我有桌子
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;
}
有这样的错误......
错误:此行productbindingsource.DataSource = produc;
不支持异常被用户代码清除 无法比较'System.Linq.IQueryable`1'类型的元素。 只有原始类型(如Int32,String和Guid)和实体 支持类型。
答案 0 :(得分:1)
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()
,它从初始查询中获取第一个结果。
答案 1 :(得分:0)
您尝试将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
编辑 - 可能不是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
};