2011-08-19 41 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 ... –