c# - 使用动态 Linq 查询子字符串时出错

标签 c# sql entity-framework linq dynamic-linq

我正在尝试使用动态 linq 从使用实体的数据库中获取一部分人 框架(EF)。使用 contains 操作时遇到问题。这是实体 对于人员表:

public class Person
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
}

这是一个成功运行的查询。

var people = personContext
    .People
    .OrderBy("id asc")
    .Skip(0)
    .Take(5)
    .ToList();

请注意,我在 OrderBy 方法中使用了动态 linq。但是,当我尝试申请时 过滤,我得到一个异常。

var people = personContext
    .People
    .Where("id.Contains(15)")
    .OrderBy("id asc")
    .Skip(0)
    .Take(5)
    .ToList();

我想取回的是 ID 中包含子字符串“15”的人的子集,例如:

"015", "115", "151", "152", etc.

当我执行代码时,出现以下错误。

System.Linq.Dynamic.ParseException was unhandled by user code
    Message=No applicable method 'Contains' exists in type 'String'

确定 Id 字段是否包含字符串“15”的语法是什么?

最佳答案

What is the syntax for determining if the Id field contains the string "15"?

嗯,绝对不是 .Where("id.Contains(15)") 试图用 numeric 调用方法 Contains值 15。

根据documentation ,您可以使用字符串文字:

.Where("id.Contains(\"15\")")

substitution values :

.Where("id.Contains(@0)", "15")

关于c# - 使用动态 Linq 查询子字符串时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39134166/

相关文章:

c# - 验证从 oauth2/v4/token 收到的 Google OAuth id token

SQL 查询返回无效序列

c# - DbMigration 使用数据移动列

C#在每个循环中从列表中获取随机整数

c# - 将大型 xml 文件插入 xml 列的最佳方法(在远程 SQL Server 上)

mysql - SQLBuddy:如何选择数据库?

entity-framework - 在 Entity Framework 中禁用外键暴露?

entity-framework - 如何预编译 Entity Framework 代码优先查询?

c# - C#抛出异常后的return语句

sql - 优化执行时间为 1 分钟的简单查询