C# 动态 Linq : Strings are assumed to be integers?

标签 c# mysql sql linq

我正在使用此处找到的 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/

相关文章:

c# - 为什么找不到方法 app.UseSwaggerUI(...)?

c# - 将上下文传递给静态方法会导致 Android 中的内存泄漏吗?

C# 将字符串复制到字节缓冲区

c# - AddressEntry 中的通讯组列表是一个AddressEntry? - C#

php - 类型定义字符串中的元素数量与绑定(bind)变量的数量不匹配

mysql - 查询返回上个月的变化

0.0.0.0 :3306 rather than 127. 0.0.1:3306 上 Windows-7(64 位)上的 MySQL

mysql - 如何将某些列及其数据从csv文件导入mysql phpmyadmin

java - 如何在 Oracle 中使用 Blob 对象作为 MapSqlParameterSource 的参数

mysql - 查找两个表中的最大记录