linq with Any and sql_variants

173 views Asked by At

i have a problem with sql_variants

i have 2 tables and a 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

I like to select everything from tbale 1 and if there is a value entered for the id of table 1 in table2 i like to get the value from there. This works great with strings (or at least one of the 'wert' columns beeing a string. But if both 'wert' columns are sql_variants, i do get nasty outputs:

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

as text inside the grid where i display the stuff.

Here is some sample code

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]

That "AS [value]" looks "strange"

Can someone tell me why this query won't work with sql_variants?

thank you

_rene

Oh what i just realized: Linq is doing 2 additional querys (for every entry that is poresent in the second table:

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

And it seems like both values are merged to the returning DTO as a list of Objects

Edit: Ok i got this working but not with .Any but left outer join

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)})

However it would be very great to know, why the .Any "solution" does not work

0

There are 0 answers