2013-11-25 33 views
3

我已經構建了一個查詢來從兩個表中返回它們通過內部聯接進行聯接的數據。雖然,因爲查詢看起來不錯,但當我嘗試從查詢中訪問所選字段名稱時,出現錯誤消息。如何在此查詢中使用.SingleOrDefault()函數。任何人都可以幫助我如何繼續。如何使用實體框架從數據庫獲取數據6

private void FindByPincode(int iPincode) 
    { 
     using (ABCEntities ctx = new ABCEntities()) 
     { 
      var query = from c in ctx.Cities 
         join s in ctx.States 
         on c.StateId equals s.StateId 
         where c.Pincode == iPincode 
         select new { 
           s.StateName, 
           c.CityName, 
           c.Area}; 

      // var query = ctx.Cities.AsNoTracking().SingleOrDefault(_city => _city.Pincode == iPincode); 

      if (query != null) 
      { 
       cboState.SelectedItem.Text =query.State;  //Getting error "Could not found" 
       cboCity.SelectedItem.Text = query.CityName;  //Getting error "Could not found" 
       txtArea.Text = query.Area;      //Getting error "Could not found" 

      } 

     } 
    } 

在此先感謝。

+0

錯誤是「'System.Linq.IQueryable '不包含'StateName'的定義,也沒有接受'System.Linq.IQueryable '可以找到(你是否缺少using指令或程序集引用?)「 – Jaan

回答

5

試試這個:

using (ABCEntities ctx = new ABCEntities()) 
    { 
     var query = (from c in ctx.Cities 
        join s in ctx.States 
        on c.StateId equals s.StateId 
        where c.Pincode == iPincode 
        select new { 
          s.StateName, 
          c.CityName, 
          c.Area}).First().SingleOrDefault(); 

     if (query != null) 
     { 
      cboState.SelectedItem.Text =query.State;   
      cboCity.SelectedItem.Text = query.CityName;  
      txtArea.Text = query.Area;       
     } 
    } 
+0

我看到了你的代碼,但不明白你爲什麼使用.First( )和SingleOrDefault()都可以獲取數據....'.First()。SingleOrDefault();'請問你能告訴我原因嗎? –

0

是否可以選擇一個名爲StateName的字段,然後訪問狀態。

cboState.SelectedItem.Text =query.State;  



cboState.SelectedItem.Text =query.StateName;  

請提供錯誤的更多細節和你的代碼的類結構

+0

請告訴我如何分配查詢的值... – Jaan

0

這裏有一個類似的情況如何爲我工作:

using (ABCEntities ctx = new ABCEntities()) 
{ 
     var query = (from c in ctx.Cities 
        join s in ctx.States 
        on c.StateId equals s.StateId 
        where c.Pincode == iPincode 
        select new { 
          s.StateName, 
          c.CityName, 
          c.Area}).Single(); 

     if (query.Any()) 
     { 
      cboState.SelectedItem.Text =query.State; 
      cboCity.SelectedItem.Text = query.CityName; 
      txtArea.Text = query.Area; 
     } 
} 

請注意,我在那裏使用了query.Any(),這是因爲query!= null將始終返回true。然而any()檢查一個查詢是否返回了一個或多個記錄,如果是的話Any()返回true,如果一個查詢沒有返回任何記錄,則Any()返回false。

+0

如果查詢返回默認值(如果不是single())會怎麼樣。然後它會變成一個錯誤/異常。 –

+0

@SorangwalaAbbasali您可以使用SingleOrDefault()來處理這種情況。 –

相關問題