[英]how to get single value by using entity framework
I have a 我有一个
table product with colums product_id
prodcut_name
category_id
another table category
category_id
category_name
and i am populating these product details using datagridview that working fine 我正在使用datagridview填充这些产品详细信息,工作正常
and i need to get the categoryname for selected row in datagridview for that i have done like this.... 我需要获取datagridview中所选行的类别名称,因为我已经这样做....
private void productGridview_Cellclick(object sender, DataGridViewCellEventArgs e)
{
string productname = Convert.ToString(selectedRow.Cells["productnam"].Value);
var categoryids = from cats in abc.products
where cats.product_Name.Equals(productname)
select cats.category_Id;
var catogynames = from categorytypes in abc.categories
where categorytypes.category_Name.Equals(categoryids)
select categorytypes.category_Name;
string categorynames = catogynames;
}
got an 得到了
error : cannot implicitly convert type sysytem.linq.iqueryble<string> to string ...
what i need to do to get the single category name for selected cell in productgridview productnam column 我需要做什么来获得productgridview productnam列中所选单元格的单个类别名称
any suggestions.. pls .. 任何建议..请..
many thanks.... 非常感谢....
Modified Code: got an error : 修改代码:出错:
not supported exception:
Unable to create a constant value of type 'System.Object'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
Your query is returning a query object that behaves like a collection. 您的查询返回的行为类似于集合的查询对象。 You can use First
, FirstOrDefault
, Single
, or SingleOrDefault
to retrieve the first or single item from the query respectively. 您可以使用First
, FirstOrDefault
, Single
或SingleOrDefault
分别从查询中检索第一个或单个项目。
var categoryid = (from cats in abc.products
where cats.product_Name.Equals(productname)
select cats.category_Id).SingleOrDefault();
string categoryname = (from categorytypes in abc.categories
where categorytypes.category_Name.Equals(categoryid)
select categorytypes.category_Name).SingleOrDefault();
your problem with casting is here 你的铸造问题就在这里
string categorynames = catogynames;
catogynames
is IQueryble
. catogynames
是IQueryble
。 You can do something like this, 你可以这样做,
List<String> categorynames = catogynames.ToList();
Or you can iterate through catogynames
. 或者你可以迭代catogynames
。
PS please review your variable names :D. PS请查看您的变量名称:D。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.