首页 > 解决方案 > 如何检查 ef 核心中逗号分隔的连接列中是否存在字符串?

问题描述

所以我试图查看一个字符串是否存在于多个用逗号分隔的连接列中:

例如,我的表有列address, citystate如下所示:

地址 城市 状态
123 街 农庄
456路 奥斯汀 德克萨斯州
789路 相对湿度

所以逗号分隔的连接字符串看起来像这样:

123 St., Farmtown, MN
456 Road, Austin, TX
789 Way, Emerald, RH

注意每个逗号后面的空格

我想要的是

使用 LINQ 方法语法,能够输入像“St., Farm”这样的字符串并获取第一行

我试过的

    var inputString = "St., Farm"

    Expression<Func<MyTable, bool>> validAddressInput =
    x => string.Concat(x.Address, ", ", x.City, ", ", x.StateProvince)
    .Contains(inputString);

    var results = _context.MyTable.Where(validAddressInput).ToList()

    // results should contain that 1st row

结果

InvalidOperationException - 无法翻译 LINQ 表达式“...”。要么以可翻译的形式重写查询,要么通过插入对“AsEnumerable”、“AsAsyncEnumerable”、“ToList”或“ToListAsync”的调用显式切换到客户端评估。

很明显,它似乎无法将其转换string.Concat(...)为原始 SQL,但我不确定将其更改为什么。

标签: c#stringentity-framework-core

解决方案


        public async Task<List<MyTable>> Search(string inputString)
    {
        var param = Expression.Parameter(typeof(MyTable), "table");
        var expression = GetExpression(param, nameof(MyTable.State), nameof(MyTable.Address), nameof(MyTable.City), inputString);
        var lambda = Expression.Lambda<Func<MyTable, bool>>(expression, param);

        return await _context.MyTable.Where(lambda).ToListAsync();
    }

        private static readonly MethodInfo ContainsMethod = typeof(string).GetMethod(nameof(string.Contains), new Type[] { typeof(string) });
    private static readonly MethodInfo ConcatMethod = typeof(string).GetMethod(nameof(string.Concat), new Type[] { typeof(string), typeof(string), typeof(string) });


    private static Expression GetExpression(ParameterExpression param, string propertyName1, string propertyName2, string propertyName3, string searchText) =>
         Expression.Call(Expression.Call(ConcatMethod, Expression.Property(param, propertyName1), Expression.Property(param, propertyName2), Expression.Property(param, propertyName3)),
                    ContainsMethod, Expression.Constant(searchText));

推荐阅读