2017-10-28 101 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

相关问题