我正在使用此处找到的 System.Linq.Dynamic 库,它只是 Microsoft 库的上传,可通过 NuGet 访问:https://github.com/kahanu/System.Linq.Dynamic
在我的代码中,我有一个函数可以从数据库中获取与某个属性匹配的对象列表。它需要尽可能灵活,因此参数由三个字符串组成;
- 一个用于“order by”语句
- 一个用于与名称匹配的属性
- 一个代表预期属性(property)的值(value)
这是给我带来麻烦的代码行:
public IQueryable<T> GetByProperty(string propertyName, string propertyValue,
string orderStatement)
{
return _context.Set<T>()
.OrderBy(orderStatement)
.Where(propertyName + " = " + propertyValue);
}
以下是可能的情况;
- propertyValue 仅包含数字:查询运行良好。
propertyValue 以数字开头,但其中包含字母:出现以下错误:
Operator '=' incompatible with operand types 'String' and 'Int32'
propertyValue 是其他值:出现以下错误:
No property or field '[the first part of the "propertyValue string, up until it meets an empty space, a "-" or some other specific characters]' exists in type '[Class name of <T>]'
我尝试使用单引号括住我的字符串,但随后出现错误:'Character literal must contain exactly one character'
我还拼命尝试在末尾添加“.ToString()”以尝试欺骗某些东西使其工作,但我发现了错误:Digit expected
.
是否有另一种方法可以在 Linq 和 Dynamic Linq 中使用“Where”子句,以支持我尝试使用此结构的灵 active ?
最佳答案
您需要知道属性的类型并相应地设置值的格式。如果是字符串,请将其用双引号引起来。即 name = "John"
但 age = 20
。
这并不取决于该值是否看起来像数字。
- 如果属性的类型是数字类型,则值也必须是数字,并且不能用引号引起来。
- 如果属性的类型是字符串,则该值必须用双引号引起来,即使该值是数字(例如
code = "3"
)。
关于C# 动态 Linq : Strings are assumed to be integers?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54225416/