[英]LINQ to Entities - How to return a single string value from entity
我在asp mvc 3 app工作。 我有一個名為History的模型/實體。 我有一個返回一個值的linq查詢。 根據我的操作,當調用方法時,我在控制器中得到“對象未設置為實例”錯誤,或者我得到“無法隱式地從字符串轉換為類型Models.History”。 所以我在尋求解決方面的幫助,我只需要投射它還是什么?
這是給出“對象未設置”錯誤的方法:
public string GetPastAbuseData(int Id)
{
var query = (from h in _DB.History
where h.ApplicantId.Equals(Id)
select h.AbuseComment).FirstOrDefault();
return query.ToString();
}
Controller: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();
}
感謝您的時間。
您正在從HistoryObject
中選擇AbuseComment
屬性(它是字符串)。 因此,您的代碼嘗試將字符串轉換為History
。 只需返回整個History
實體:
public History GetPastAbuseData(int Id)
{
return (from h in _DB.History
where h.ApplicantId.Equals(Id)
select h).SingleOrDefault();
}
同樣在第一種情況下, query
將是字符串類型。 您不需要在此變量上調用ToString
。 更重要的是,當你陷入OrDefault()
情況時,你會有NullReferenceException
。
public string GetPastAbuseData(int Id)
{
return (from h in _DB.History
where h.ApplicantId.Equals(Id)
select h.AbuseComment).FirstOrDefault();
}
你的第一個例子很好,你只需要檢查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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.