在 LINQ 的 where 子句中使用 .NET 字符串函数

Using .NET string functions in where clause of LINQ

如何在这样的 LINQ 查询中使用 .NET 框架字符串函数?

var accounts = from a in orgContext.CreateQuery("account")
                      where a["telephone1"].ToString().Replace("-","") == "1234567890"
                      orderby a["name"]
                      select new { id = a["accountid"], name = a["name"], telephone1 = a["telephone1"]};

这以错误结束:

Invalid 'where' condition. An entity member is invoking an invalid property or method.

更新
在生成实体 类 之后,我针对 SQL 服务器中的测试数据库尝试了这个 LINQ 查询,它 returns 结果成功:

from Account in db.Account
where Account.Telephone1.Replace("-", "").Substring(Account.Telephone1.Replace("-", "").Length - 10, 10) == "1234567890"
select new {
  Account.AccountId,
  Account.Name,
  Account.Telephone1
}

但由于我在 Dynamics CRM 中使用 LINQ 查询,如第一个代码示例中所示(项目中没有实体 类),应用程序最终得到 运行 -时间错误。

PS:我不能使用早期绑定实体,因为当客户将任何属性添加到 Dynamics CRM 实体时,这可能会破坏解决方案。

您可以使用 SqlFunctions.StringConvert 方法。

这是msdn link https://msdn.microsoft.com/en-us/library/dd466166.aspx

var accounts = from a in orgContext.CreateQuery("account")
                                  where SqlFunctions.StringConvert(a["telephone1"]).Replace("-","") == "1234567890"
                                  orderby a["name"]
                                  select new { id = a["accountid"], name = a["name"], telephone1 = a["telephone1"] };

这部分查询:a["telephone1"].ToString().Replace("-","") 无法转换为有效的 SQL 语句或任何基础域语言。使用 linq-to-entities 时,您的查询需要以底层数据库的 SQL 风格或实体的域语言(如果不是 SQL 为基础)来表达。使用 linq-to-objects 时,情况并非如此,您的查询将有效。

您可以在 linq-to-entity 查询中使用 SqlFunctions 中的静态方法,但正如您已经注意到的那样,您实际上没有太多的字符串操作选项。此外,您的基础实体是 dynamics-crm,因此除非您直接连接到 SQL 数据库,否则您可能无法使用 SQL 语句。

在您的情况下,您需要先将电话字符串转换为正确的格式,然后再在查询中使用它。但是,我看到您正在与常量字符串 "1234567890" 进行比较,因此不是从动态对象中删除破折号,而是将破折号放入常量字符串中,例如 "123-456-7890" 假设这是一部电话根据您的查询建议的数字。

你不能这样做。 Dynamics CRM LINQ 提供程序不支持此功能,因为 QueryExpression 不支持此搜索。

https://msdn.microsoft.com/en-us/library/gg334607.aspx

Queries are built using standard language, but internally uses QueryExpression so is limited to the features of QueryExpression.

要执行此搜索,您需要在 CRM 中有一个已清理的值。我之前在进行 TAPI (telephone) 集成时遇到过这个问题。解决方案是在 Create/Update 上创建一个插件,该插件对 phone 数字进行替换并将值放在不同的字段中(即 "new_cleanphonenumber"),然后可以搜索该字段。

您可以使用相同的清理代码编写一个简单的命令行实用程序来遍历和更新所有现有值。