【问题标题】:How to escape string for dynamic linq where clause如何为动态 linq where 子句转义字符串
【发布时间】:2021-06-21 12:59:17
【问题描述】:

我正在使用 Dynamic LINQ 使用动态 where 子句查找记录。我有 Person 类的实例

public class Person
{
   public string Name {get;set;}
   public int Age {get;set;}
   public string Address {get;set;}
}

var person = new Person()
{
   Name = "Foo Bar",
   Age = 25,
   Address = "1234 ABC \"XYZ\" Road"
}

假设我已经拥有要包含在 where 子句中的属性集合。

var properties = new string[] {"Name","Age","Address"};

我正在使用反射构造 where 子句。根据文档

如果值是字符串,那么我们需要在双引号中对其进行转义。

where 子句构造

var type = person.GetType();
var clause = "";
foreach (var propertyName in properties)
{
    var p = type.GetProperty(propertyName);
    var val = p.GetValue(person);
    if (val != null)
    {
        if (p.PropertyType == typeof(string))
        {
            val = $"\"{val}\"";
        }

        clause = clause == "" ? $"{propertyName} == {val}" : $"{clause} && {propertyName} == {val}";
    }
}

找人

var found = await dbContext.Persons
             .Where(condition)
             .ToListAsync();

这是失败的,因为它没有正确转义地址值。正确的子句应该是

"Name == \"Foo Bar\" && Age == 25 && Address= \"1234 ABC \\\"XYZ\\\" Road\""

.NET 中是否有可以转义字符串的库?我试过 Regex.Escape() 没用

【问题讨论】:

    标签: linq linq-expressions dynamic-linq dynamic-linq-core


    【解决方案1】:

    DynamicLinq 支持用于此目的的参数。见https://dynamic-linq.net/basic-simple-query#strongly-typed-linq-versus-dynamic-linq

    在您的情况下,棘手的事情是将参数及其名称作为动态值进行跟踪。我认为这样的事情应该可行。

    var type = person.GetType();
    var clauses = new List<string>();
    var parameters = new List<object>();
    foreach (var propertyName in properties)
    {
        var p = type.GetProperty(propertyName);
        var val = p.GetValue(person);
        if (val != null)
        {
            var parameterName = $"@{parameters.Count}";
            parameters.Add(val);
            clauses.Add($"{propertyName} == {parameterName}");
        }
    }
    var condition = string.Join(" && ", clauses);
    ...
    var found = await dbContext.Persons
                 .Where(condition, parameters.ToArray())
                 .ToListAsync();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      相关资源
      最近更新 更多