1

我对 sql_variants 有疑问

我有 2 张桌子和一个 DTO

'struct A_Table1
' id (int)(not null)
' wert (sql_variant)(not null)

'struct A_Table2
' id (int)(not null)
' wert (sql_variant)(not null)

Private Class DTO
    Public Property id As Integer
    Public Property wert As Object
End Class

我喜欢从 tbale 1 中选择所有内容,如果在 table2 中为表 1 的 id 输入了值,我想从那里获取值。这适用于字符串(或至少一个 'wert' 列作为字符串。但如果两个 'wert' 列都是 sql_variants,我会得到令人讨厌的输出:

System.Collections.Generic.List`1[System.Object]

作为我显示内容的网格内的文本。

这是一些示例代码

Private Sub Button2_Click_1(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        Dim q = (From p In db.A_Table1s Select New DTO With {
                 .id = p.id,
                 .wert = If(db.A_Table2s.Any(Function(f) f.id = p.id And Not f.wert Is Nothing),
                            (From v In db.A_Table2s Where v.id = p.id Select v.wert).FirstOrDefault,
                            p.wert)
        })

        bs3.DataSource = q
        grd.DataSource = bs3
End Sub

And the generated SQL

SELECT [t0].[id], 
    (CASE 
        WHEN EXISTS(
            SELECT NULL AS [EMPTY]
            FROM [dbo].[A_Table2] AS [t1]
            WHERE [t1].[id] = [t0].[id]
            ) THEN 1
        ELSE 0
     END) AS [value], [t0].[wert]
FROM [dbo].[A_Table1] AS [t0]

“AS [value]”看起来“奇怪”

有人能告诉我为什么这个查询不适用于 sql_variants 吗?

谢谢你

_rene

哦,我刚刚意识到:Linq 正在执行 2 个额外的查询(对于第二个表中的每个条目:

SELECT TOP (1) [t0].[wert]
FROM [dbo].[A_Table2] AS [t0]
WHERE [t0].[id] = @x1
-- @x1: Input Int (Size = -1; Prec = 0; Scale = 0) [1]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1

SELECT TOP (1) [t0].[wert]
FROM [dbo].[A_Table2] AS [t0]
WHERE [t0].[id] = @x1
-- @x1: Input Int (Size = -1; Prec = 0; Scale = 0) [3]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1

似乎这两个值都作为对象列表合并到返回的 DTO

编辑:好的,我得到了这个工作,但没有使用 .Any 但左外连接

Dim q = (From p In db.A_Table1s
             Group Join v In db.A_Table2s On p.id Equals v.id Into Group From v In Group.DefaultIfEmpty() Select New DTO With
            {.id = p.id, .wert = If(v.wert Is Nothing, p.wert, v.wert)})

但是,很高兴知道为什么.Any“解决方案”不起作用

4

0 回答 0