2012-11-02 264 views
6

我正在asp mvc 3應用程序中工作。我有一個名爲History的模型/實體。我有一個返回一個值的linq查詢。根據我所做的事情,當調用方法時,我在控制器中獲取「未設置爲實例的對象」錯誤,或者得到「無法從字符串隱式轉換爲鍵入Models.History」。所以我在尋求幫助解決,我是否需要投它或什麼?LINQ to Entities - 如何從實體返回單個字符串值

下面是給出了 '對象未設置' 錯誤的方法:

public string GetPastAbuseData(int Id) 
{ 

    var query = (from h in _DB.History 
       where h.ApplicantId.Equals(Id) 
       select h.AbuseComment).FirstOrDefault(); 

    return query.ToString(); 
} 

控制器: vm.HistoryModel.AbuseComment = repo.GetPastAbuseData(ID);

如果我從字符串更改方法類型的歷史,我得到了「不能轉換」錯誤:

public History GetPastAbuseData(int Id) 
{ 
    return (from h in _DB.History 
      where h.ApplicantId.Equals(Id) 
      select h.AbuseComment).SingleOrDefault(); 
} 

謝謝您的時間。

回答

11

您正在從HistoryObject中選擇AbuseComment屬性(它是字符串)。因此,您的代碼嘗試將字符串轉換爲History。剛剛返回整個History實體:

在第一種情況下 query
public History GetPastAbuseData(int Id) 
{ 
    return (from h in _DB.History 
      where h.ApplicantId.Equals(Id) 
      select h).SingleOrDefault(); 
} 

也將是字符串類型。你不需要在這個變量上調用ToString。更何況,當你陷入OrDefault()的情況下,你將有NullReferenceException

public string GetPastAbuseData(int Id) 
{ 
    return (from h in _DB.History 
      where h.ApplicantId.Equals(Id) 
      select h.AbuseComment).FirstOrDefault(); 
} 
+0

lazyberezovsky,謝謝。現在看來很明顯,你指出了這一點。所以我只是回來了整個模型,並採取我認爲需要的peices。謝謝。 – BattlFrog

4

你的第一個例子很好,你只需要檢查null。

public string GetPastAbuseData(int Id) 
{ 

    var query = (from h in _DB.History 
      where h.ApplicantId.Equals(Id) 
      select h.AbuseComment).FirstOrDefault(); 

    return query == null ? string.empty : query; 
} 
+0

字符串具有「null」值是可以的。你爲什麼用'String.Empty'替換它? –

+0

很多人不喜歡空值,即使是字符串。我通常在這種情況下合併:返回查詢? 「」; – Dismissile

2

您可以使用空合併運算符來檢查是否爲空並返回string.Empty如果爲null。 ?? Operator

public string GetPastAbuseData(int Id) 
{ 
    return _DB.History.FirstOrDefault(h=>h.ApplicantId.Equals(Id)).Select(h=>h.AbuseComment) ?? string.Empty; 
}