linq - 使用 IsNullOrWhitespace 检查从 IQueryable 中选择值

标签 linq linq-to-entities iqueryable

我正在尝试使用 IQueryable 表达式执行以下操作:

(from Person p in s
   select new
   {
           label = p.FirstName + " "
       + (string.IsNullOrWhiteSpace(p.MiddleName) ? p.MiddleName + " " : "")
                   + p.LastName,
       value = p.Id
       }).ToList();

我收到以下错误:

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

解决这个问题的方法是什么?

最佳答案

String.IsNullOrWhitespace 是字符串对象的静态函数,不能与 Entity Framework 查询一起使用,而 p.FirstName.StartsWith("S") 是实体属性的方法,可以被使用。

要回答您的问题,您将不得不推出自己的内联。试试这个:

(from Person p in s
   select new
   {
       label = p.FirstName + " "
       + ((p.MiddleName != null && p.MiddleName != string.Empty) ? p.MiddleName + " " : "")
                   + p.LastName,
       value = p.Id
   }).ToList();

关于linq - 使用 IsNullOrWhitespace 检查从 IQueryable 中选择值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13813008/

相关文章:

c# - 使用 Linq to Entities 执行字符串搜索

c# - 如何比较linq查询中where子句中的泛型

LINQ:字段不是引用字段

c# - 从 IQueryable<T> 转换为 T

vb.net - 通过 LINQ 向树添加节点在运行时创建 "query operator not supported"

c# - 在c#中将对象转换为Ushort数组

c# - 在 LINQ 中使用命名元组数组

c# - IQueryable.ToList 方法搞乱了 T-SQL 排序顺序

c# - ElasticSearch NEST-先按GroupBy再按OrderBy

c# - 修改 Entity Framework 的表达式树,尽可能接近 T-SQL translation\execution