加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何使用实体框架获取单个值

发布时间:2020-12-15 08:21:13 所属栏目:百科 来源:网络整理
导读:我有一个 table product with colums product_id prodcut_name category_id another table category category_id category_name 我正在使用datagridview填充这些产品详细信息,工作正常 我需要获取datagridview中所选行的类别名称,因为我已经这样做…. privat
我有一个
table product with colums product_id 
                               prodcut_name
                               category_id

                another table  category 
                               category_id
                               category_name

我正在使用datagridview填充这些产品详细信息,工作正常

我需要获取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;    

       }

得到了

error : cannot implicitly convert type sysytem.linq.iqueryble<string> to string ...

我需要做什么来获得productgridview productnam列中所选单元格的单个类别名称

任何建议..请..

非常感谢….

修改代码:
得到一个错误:

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.

解决方法

您的查询返回的行为类似于集合的查询对象.您可以使用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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读