如何为动态 linq where 子句转义字符串

How to escape string for dynamic linq where clause

我正在使用 Dynamic LINQ 通过动态 where 子句查找记录。我有 Person class

的实例
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 子句。基于文档

if the value is string then we need to escape it in the double quotes.

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() 没用

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();