c# - 如何检查 ef 核心中逗号分隔的连接列中是否存在字符串?
问题描述
所以我试图查看一个字符串是否存在于多个用逗号分隔的连接列中:
例如,我的表有列address
, city
,state
如下所示:
地址 | 城市 | 状态 |
---|---|---|
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,但我不确定将其更改为什么。
解决方案
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));
推荐阅读
- xml - XSL将一个值乘以选择值中的一个值
- java - 如何在没有 id 的情况下使 menuItem 不可见?
- machine-learning - 在 SVM 模型中,当我将测试大小减小到 0.06 时,结果是否可行
- pascalscript - 将新的 ifclause 添加到过程后出现调试错误“;预期”
- google-app-engine - GAE 标准异步获取不起作用
- python - 注释子类的方法?
- php - 有没有办法从作曲家创建“我们使用的图书馆”页面?
- javascript - 使用托管应用程序在客户端打印
- point-clouds - 使用 PDAL 的点云密度可视化
- java - Android Recyclerview 以编程方式设置项目的位置