LINQ to Entities - 方法无法转换为商店表达式

时间:2017-10-28 21:23:33

标签: c# asp.net entity-framework linq

同样的查询在.Net 3.5中有效但在.Net 4.5.2中没有 这里有很多帖子都有相同的错误,并尝试了几乎所有但没有用的。 我已将所有内容提取到一个单独的变量中进行查询。我仍然得到错误 -

  

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();
                }
            }
}

我不确定还有什么可以更改以使此查询运行。

1 个答案:

答案 0 :(得分:2)

在使用string.Format之前,您需要使用“LINQ to Objects”来执行AsEnumerable()或使用ToList()Select插入字符串:

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)
                });

请注意,LINQ to Entities无法识别string.Format方法将其转换为SQL命令,因此查询结果实现到内存是必要的。

注意:如果您在使用Any()方法之前仍需要LINQ to Entities查询,则可以使用SqlFunctions.StringConvert,但并非所有SQL提供程序都能将其转换为SQL语句。

相关问题:

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