2017-10-28 65 views
0

相同的查詢在.Net 3.5中工作,但不在.Net 4.5.2中 在這裏有很多帖子都有相同的錯誤,並且幾乎嘗試了所有的但不是使用。 我已經提取了一切到一個單獨的變量進行查詢。我仍然收到錯誤 -LINQ to Entities - 方法不能轉換爲商店表達式

LINQ to Entities無法識別方法'System.String Format(System.String,System.Object)'方法,並且此方法無法轉換爲存儲表達式。

private void LoadAppointmentData() 
     { 
      var user = Session["user"].ToString(); 
      var userFirstName = db.Users.SingleOrDefault(u => u.FirstName == user); 

      var userFN = userFirstName.username; 
      var chwWorker = from c in db.PatientContacts 
          where c.UserName == userFN && 
           (c.PCP_Status == "Appointment Made" || c.PCP_Status_AWC == "Appointment Made" 
            || c.PCP_Status_AWDV == "Appointment Made" || 
           (c.PCP_Status == "RX for Mamogram" && c.Status == "Appointment Made")) 
          orderby c.PCP_Status_Date descending 
          select new 
          { 
           Id = c.MemberID, 
           Name = c.PatientFirstName + " " + c.PatientLastName, 
           PCP_Appt = $"{c.PCP_Status_Date:d}", 
           Mammogram_Appt = $"{c.StatusDate:d}", 
           Phone = GetPhone(c.MemberID) 
          }; 
      if (chwWorker.Any()) 
      { 
       if (grvAppointmentList != null) 
       { 
        pnlAppointmentFollowUp.Visible = true; 
        grvAppointmentList.DataSource = chwWorker; 
        grvAppointmentList.DataBind(); 
       } 
      } 
} 

我不知道還有什麼可以改變,使這個查詢運行。

+3

'$ 「{c.PCP_Status_Date:d}」'[是'String.Format'(https://docs.microsoft.com/en-us/ DOTNET/CSHARP /語言參考/關鍵字/內插值字符串)。我假設你知道錯誤的含義。 –

+0

但在早期版本中工作... – Ron

+3

不,string.Format從來沒有在實體框架中受支持的方法。我假設你在.Net 3.5中使用了LINQ-to-SQL,它可以自動切換到LINQ查詢中無法轉換爲SQL的部分的客戶端評估。 –

回答

1

您需要使用Select之前,使用「LINQ到對象」使用AsEnumerable()ToList()執行string.Format或內插字符串:

var chwWorker = (from c in db.PatientContacts 
       where c.UserName == userFN && 
        (c.PCP_Status == "Appointment Made" || c.PCP_Status_AWC == "Appointment Made" 
         || c.PCP_Status_AWDV == "Appointment Made" || 
        (c.PCP_Status == "RX for Mamogram" && c.Status == "Appointment Made")) 
       orderby c.PCP_Status_Date descending select c) 
       .AsEnumerable() // or 'ToList()' 
       .Select(c => new 
       { 
        Id = c.MemberID, 
        Name = c.PatientFirstName + " " + c.PatientLastName, 
        PCP_Appt = $"{c.PCP_Status_Date:d}", 
        Mammogram_Appt = $"{c.StatusDate:d}", 
        Phone = GetPhone(c.MemberID) 
       }); 

注意string.Format方法不受LINQ公認的實體,以它作爲翻譯一個SQL命令,因此查詢結果具體化到內存是必要的。

注意:如果在使用Any()方法之前仍然希望LINQ to Entities查詢,但不是所有SQL提供者都能夠將它轉換爲SQL語句,則可以使用SqlFunctions.StringConvert

相關的問題:

LINQ to Entities does not recognize the method 'System.String Format

+0

謝謝,將嘗試您的解決方案並將更新 – Ron

+0

Thanks @ Tetsuya Yamamoto - 我必須使用Select運算符來查詢才能像這樣工作「... order by c.PCP_Status_Date降序選擇c).AsEnumerable()...」它起作用現在好了。其他方面,它會拋出一個「查詢主體必須以select子句或group子句結束。感謝您幫助解決此問題。 – Ron

相關問題