You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SqlKata查询返回重复列问题求助(VS2022+SQL Express)

解决SqlKata查询结果在WinForm DataGrid中列重复的问题

以下是几个针对性的解决思路:

  • 转换查询结果为强类型或DataTable
    SqlKata默认Get()方法返回动态对象集合,WinForm DataGrid处理动态类型时容易因元数据识别重复列。可以直接转换成DataTable,或者用强类型实体接收结果:
    转换成DataTable的示例:

    Dim dt As DataTable = db.Query(table).GetDataTable()
    DataGridView1.DataSource = dt
    

    用强类型实体的示例:

    ' 先定义对应表结构的实体类
    Public Class RecordEntity
        Public Property sid As Integer
        Public Property Start_Date As DateTime
        Public Property Subject As String
        Public Property Comment As String
        Public Property isDeleted As Boolean
    End Class
    
    ' 查询时指定实体类型
    Dim objFind = db.Query(table) _
            .WhereContains(field1, term1) _
            .OrderByDesc("Start_Date") _
            .Select("sid", "Start_Date", "Subject", "Comment", "isDeleted") _
            .Get(Of RecordEntity)()
    DataGridView1.DataSource = objFind.ToList()
    
  • 检查DataGrid的AutoGenerateColumns设置
    如果手动给DataGrid添加过列,同时开启了AutoGenerateColumns = True,会导致手动列和自动生成的列重复。可以关闭自动生成列后手动绑定,或者只保留自动生成:

    DataGridView1.AutoGenerateColumns = False
    ' 手动添加列并绑定对应数据字段
    DataGridView1.Columns.Add(New DataGridViewTextBoxColumn() With {
        .Name = "sidColumn",
        .HeaderText = "记录ID",
        .DataPropertyName = "sid"
    })
    ' 依次添加其他列...
    DataGridView1.DataSource = objFind
    
  • 验证SqlKata生成的SQL语句
    用ToString()输出实际生成的SQL,确认是否存在重复列:

    Dim generatedSql = db.Query(table).Select("sid", "Start_Date").ToString()
    Debug.WriteLine(generatedSql)
    

    如果SQL里确实重复选择了列,检查Query构建过程中是否重复调用了Select或其他导致列重复的方法。

  • 排查数据库表结构
    确认数据库表本身没有大小写不同但名称相同的列(SQL Server默认不区分大小写,这类列会被SqlKata返回为重复字段),同时检查表结构是否存在重复定义的列。

内容的提问来源于stack exchange,提问作者Greg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 04:07:02