簡體   English   中英

LINQ to Entities - 如何從實體返回單個字符串值

[英]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;
 }

您可以使用null coalescing運算符來檢查是否為null,如果為null則返回string.Empty。 ?? 操作者

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM