【问题标题】:System.NotSupportedException while trying to filter by ID C#尝试按 ID C# 过滤时出现 System.NotSupportedException
【发布时间】:2016-06-10 07:50:45
【问题描述】:

我将此代码用作 datagridview 中的过滤器:

private void consultarPorCriterio()
    {
        
        var inspec = from ins in entities.Inspeccions
                        where (ins.Ralladuras.StartsWith(txtTextoABuscar.Text) ||
                               ins.Repuesta.StartsWith(txtTextoABuscar.Text)||
                               ins.ID.ToString().StartsWith(txtTextoABuscar.Text)
                              )
                        select ins;
        dgvInspeccion.DataSource = inspec.ToList();
    }

如果我删除它会过滤:

ins.ID.ToString().StartsWith(txtTextoABuscar.Text)。

如果我不删除那部分代码,我会收到此错误:

异常未处理... mscorlib.dll 中的“System.NotSupportedException”

附加信息:LINQ to Entities 无法识别方法“System.String ToString()”方法,并且该方法无法转换为存储表达式。

有人知道我做错了什么吗?

【问题讨论】:

  • 因为无法翻译成T-SQL,Linq to Entities无法识别,看看这个答案:stackoverflow.com/a/34061692/2946329
  • 我从我的教师程序中获取了这段代码,在他的程序中,他和我尝试做的一样,我的意思是按 ID 过滤。为什么它适用于他而不适用于我?
  • ins.ID的底层数据类型是什么?
  • 是表Inspeccion的ID。
  • 你的问题是调用了ToString()方法,不能翻译成SQL语句。

标签: c# datagridview


【解决方案1】:

您可以使用SqlFunctions.StringConvert 将int 转换为String,稍加修改您的代码可能会变成这样:

SqlFunctions.StringConvert((double)ins.ID).StartsWith(txtTextoABuscar.Text)

【讨论】:

  • 我试过了,它过滤了,但datagridview什么也没显示。
  • 您确定您的新查询正在返回数据吗?因为您绑定 datagridview 的部分似乎没问题。
猜你喜欢
  • 2015-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多