Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用动态Linq查询子字符串时出错_C#_Sql_Entity Framework_Linq_Dynamic Linq - Fatal编程技术网

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

C# 使用动态Linq查询子字符串时出错,c#,sql,entity-framework,linq,dynamic-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 s

我正在尝试使用动态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”的语法是什么?

您不能在LINQ查询中使用contains。你可以试试这个

var people = (from p in personContext.Set<People>() 
    where p.Id.Contains("15")
    orderby p.Id
    select p).Skip(0).Take(5).ToList();
var people=(来自personContext.Set()中的p)
其中p.Id.包含(“15”)
订购人p.Id
选择p).Skip(0).Take(5.ToList();

我觉得这里有误解。。。你不应该像这样使用LINQ。 首先,您需要调用接受lambdas的重载;然后在lambda中指定属性,如果调用的字符串
包含该属性。像这样:

var people = personContext
    .People
    .Where(p => p.Id.Contains("15"))
    .OrderByDescending(p => p.Id)
    .Skip(0) // You don't need this line.
    .Take(5)
    .ToList();
EF本身将完成繁重的工作,并将这些纯C代码转换为正确的SQL语句

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

当然,绝对不是
.Where(“id.Contains(15)”)
,它正试图用数值调用方法
Contains

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

或:


我错过了引语!因为我在比较字符串,所以引号是必需的。接得好!
.Where("id.Contains(\"15\")")
.Where("id.Contains(@0)", "15")