views:

290

answers:

2

With the method parameter

Int16? id

And the Linq to SQL where clause

where !id.HasValue || m.Id == id

The resulting command text for the condition in the data context is

From the visualizer:

SELECT [t0].[Id], [t0].[Name], [t0].[IsActive]
FROM [Model] AS [t0]
WHERE (CONVERT(Int,[t0].[Id])) = @p0
-------------------------------
@p0 [Int32]: 5

My mapped class has the Id as an Int16 and the database itself has the column type as a smallint, so why does the behind the scenes sql think the parameter is an integer (Int32) and not a smallint (Int16)?


Column mapping:

    [Column(IsPrimaryKey = true, DbType="SmallInt NOT NULL", CanBeNull=false)]
    public Int16 Id { get; set; }
A: 

Hmmm... I notice that you're not getting any representation of the !id.HasValue in the sql. Perhaps this is some sort of trickery related to that getting wrapped? Seems phony to me, but the only thing i can think of.

Jim Leonardo
if id.HasValue, then m.Id == id will be evaluated, otherwise the entire condition will be ignored: the where condition will not be present
CRice
+5  A: 

Change the where clause to read

where !id.HasValue || m.Id == id.Value

There is something about the nullable short that is throwing it off. I'm not sure why, but I ran into this before and found adding .Value will work.

Mike Two
WHERE (CONVERT(Int,[t0].[Id])) = @p0 becomes WHERE [t0].[Id] = @p0, which is great but @p0 is still an int32 is that normal?
CRice
It also seems best to use this where clause: if (id.HasValue) { qry = qry.Where(x => x.Id == id.Value); } --- (when using .Value with the original and when it's actually null it breaks)
CRice
The only remaining question is: why is @p0 [Int32] and not [Int16]
CRice
I've dug through the linq to sql code through reflector. It appears that at some point the id.Value gets translated to a literal, say 42, that then gets treated as an int. C# will not consider short as a possibility when dealing with a literal. It starts at int and works it's way up. I haven't been able to trace enough of the code to prove that is what it is doing but it seems that way. It also seems to do no harm.
Mike Two
Thanks for your help Mike Two
CRice