2011-08-19 79 views
5

获取单个值我有一个如何使用实体框架

 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. 

回答

7

您的查询返回的查询对象,它是有像一个集合。您可以使用FirstFirstOrDefault,SingleSingleOrDefault分别从查询中检索第一个或单个项目。

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(); 
+0

thanq ..你能为我做一个更多的青睐...是否有可能通过使用实体和c#编程方式定义映射关系.. 我想要以编程方式指定一个表的外键..是它可能..你有什么想法..... –

+0

有错误,你会请你看到我的修改代码 –

+0

你会请看看我的问题.... –

0

您拥有铸造问题是在这里

string categorynames = catogynames; 

catogynamesIQueryble。你可以做这样的事情,

List<String> categorynames = catogynames.ToList(); 

或者您也可以通过catogynames迭代。

P.S请检查您的变量名称:D。

+0

我该怎么做,因为我想发送一个值到另一个表单取决于datagridview单元格点击 –

+0

你怎么能做什么? – Incognito

+0

我可以使用foreach循环获取单个catogynames ... –