【问题标题】:Error When Querying For A Substring Using Dynamic Linq使用动态 Linq 查询子字符串时出错
【发布时间】:2023-03-13 17:54:01
【问题描述】:

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

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”的语法是什么?

【问题讨论】:

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


    【解决方案1】:

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

    好吧,绝对不是.Where("id.Contains(15)"),它试图调用 numeric 值为 15 的方法 Contains

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

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

    substitution values:

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

    【讨论】:

    • 我错过了引号!由于我正在比较字符串,因此需要引号。不错的收获!
    【解决方案2】:

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

    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 语句。

    【讨论】:

      【解决方案3】:

      您不能在 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();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-19
        • 1970-01-01
        • 2021-02-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多