2014-01-13 38 views
2

我有以下代碼。
如果沒有WType爲空,我喜歡用Key和Value的空字符串返回一個空類。我收到一個「;」的錯誤是期待。返回空值的類

的返回類型必須是:

IEnumerable<WportType> 

下面是代碼:

if (wType == "Riconda") 
{ 
    return dbContext.data_LookupValues 
     .Where(w => w.Category == "WLoc") 
     .OrderBy(w => w.SortId) 
     .Select(a => new WportType 
     { 
      Key = a.Key, 
      Value = a.Value 
     }); 

} 
else 
{ 
    return WportType 
     { 
      Key = "", 
      Value = "" 
     }; 
} 
+0

這種方法的返回類型是什麼?即使您修復了語法錯誤,但在一部分中,您正試圖返回'IQueryable ',而在另一部分中'WportType'。 –

回答

2
return new WportType // you missed new keyword also 
    { 
     Key = "", 
     Value = "" 
    }; // and ; here 

但是,這是不是在你的代碼單一的問題。 如果部分返回IEnumerable<WportType>否則部分返回簡單WportType。您應該從數據庫中選擇單個對象或其他部分收集創建與默認值:

if (wType == "Riconda") 
{ 
    return dbContext.data_LookupValues 
     .Where(w => w.Category == "WLoc") 
     .OrderBy(w => w.SortId) 
     .Select(a => new WportType { 
      Key = a.Key, 
      Value = a.Value 
     }); // or use something like FirstOrDefault() here 

} 
else 
{ 
    return new List<WportType> { 
     new WportType { Key = "", Value = "" } 
    }; 
} 
3

看來你的方法返回一個IEnumerable<WportType>。您正試圖返回單個項目。你需要一個集合內把這個包:

象下面這樣:

if (wType == "Riconda") 
    { 
     return dbContext.data_LookupValues 
      .Where(w => w.Category == "WLoc") 
      .OrderBy(w => w.SortId) 
      .Select(a => new WportType 
      { 
       Key = a.Key, 
       Value = a.Value 
      }); 

    } 
    else 
    { 
     return new[] { new WportType { Key = "", Value = "" } }; 
    } 
+1

您可能需要將第二個包裝在'new [] {..}'中,因爲第一部分返回該類型項目的可枚舉/可查詢。 –

+0

@TimS。是的,我修好了。謝謝。 – gleng

+0

不正確 - Enumerable.Empty與默認值的WportType不相同 –

0

您可能正在尋找這樣的事情:

return dbContext.data_LookupValues 
      .Where(w => w.Category == "WLoc") 
      .OrderBy(w => w.SortId) 
      .Select(a => new WportType 
      { 
       Key = !string.IsNullOrEmpty(wType) ? a.Key : "", 
       Value = !string.IsNullOrEmpty(wType) ? a.Value : "" 
      }); 

從你的問題來看,我不是很確定你的最終目標是什麼,但是這個方法將保留原始查詢的長度,並且只在你的wType爲空或者空的時候用「」來設置你的WportType的值。