c# - 如何在 linq 表达式中格式化字符串?

标签 c# linq

给定以下代码

IQueryable<string> customers = 
    from Customers in db.Customers
    where Customers.CstCompanyName.Contains(prefixText) && Customers.CstInactive == false
    select Customers.CstCompanyName + " (Phone: " + Convert.ToInt64(Customers.CstPhone).ToString("###-###-#### ####") + ")";

这是对我的 Entity Framework 的调用。我正在从数据库中返回一个电话号码。我正在尝试将其格式化为给定的格式字符串。不幸的是,当我运行它时,我收到以下错误:

LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.

所以我的问题是如何将此数据库对象作为格式化字符串返回?

谢谢!

最佳答案

我会在数据库中执行查询,但在本地格式化:

var customers = db.Customers
                  .Where(c => c.CstCompanyName.Contains(prefixText))
                  .Select(c => new { c.CstCompanyName, c.CstPhone })
                  .AsEnumerable() // Switch to in-process
                  .Select(c => c.CstCompanyName + 
                               " (Phone: " +            
                               Convert.ToInt64(Customers.CstPhone)
                                      .ToString("###-###-#### ####") + ")");

关于c# - 如何在 linq 表达式中格式化字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9535153/

相关文章:

c# - MVC 中用户过期的最佳位置

c# - 不需要的 mysql 日志来获取过程定义

c# - 我可以对整数数组使用 Sort 方法吗?

c# - 带有 Azure Linux VM 的 Couchbase

c# - 大型 LINQ 分组查询,幕后发生了什么

c# - 随机排列元素,使得任何元素都不应出现在其原始索引处

c# - 修剪数据表的所有单元格

c# - 在数组上使用 System.Linq 中的 .Any 查找字符串

c# - LINQ SELECT with Max 和 SUBQUERY 中的 Where

C#/Linq - 排序 IDictionary