如何使用VB.NET结合Dapper合并MS Access数据库列?
如何使用VB.NET结合Dapper合并MS Access列?
方案一:通过SQL查询直接合并列(推荐,适合仅需合并后字段的场景)
利用MS Access的字符串拼接语法,在SQL中直接将CodeProduct、Colorcode、Size合并为Combine字段,同时处理空值避免多余空格:
- 创建对应的数据视图类:
Public Class StockViewModel Public Property Id() As Integer Public Property Combine() As String Public Property Qty() As Integer End Class
- 修改
Getitem函数的SQL查询与返回类型:
Public Function Getitem() As IEnumerable(Of StockViewModel) ' 使用IIF处理Colorcode为空的情况,避免出现多余空格 Dim sql = "SELECT Id, CodeProduct & IIF(IsNull(Colorcode), '', ' ' & Colorcode) & ' ' & Size AS Combine, Qty FROM Stocks" Using _conn = New OleDbConnection(DbContext.GetOledbConnectionString()) Return _conn.Query(Of StockViewModel)(sql).ToList() End Using End Function
方案二:在实体类中添加计算属性(适合需要保留原字段的场景)
不需要修改SQL查询,直接在Stocks类中添加只读的Combine属性,通过代码逻辑合并字段并处理空值:
Public Class Stocks Public Property Id() As Integer Public Property CodeProduct() As String Public Property Colorcode() As String Public Property Size() As String Public Property Qty() As Integer ' 计算合并后的Combine字段 Public ReadOnly Property Combine() As String Get Dim parts As New List(Of String)() ' 仅添加非空的字段值 If Not String.IsNullOrEmpty(CodeProduct) Then parts.Add(CodeProduct) If Not String.IsNullOrEmpty(Colorcode) Then parts.Add(Colorcode) If Not String.IsNullOrEmpty(Size) Then parts.Add(Size) Return String.Join(" ", parts) End Get End Property End Class
修改后,原Getitem函数无需改动,DataGridView会自动识别Combine属性并显示对应的合并内容。
内容的提问来源于stack exchange,提问作者roy
相关产品推荐
相关产品推荐

