Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can LINQ to SQL generate TSQL containing the ISNULL function?

Tags:

c#

linq-to-sql

I was wondering whether anyone knows definitively if LINQ to SQL has the capability of generating TSQL code that contains the ISNULL function?

I'm aware that using the coalesce operator (??) in a query:

from o in Table
where (o.Field ?? 0) > 0
select o

will cause LINQ to SQL to emit the COALESCE function:

SELECT [t0].[Field]
FROM [Table] AS [t0]
WHERE (COALESCE([t0].[Field],0)) > 0

And, that using the conditional operator (?:) in a query:

from o in Table
where (o.Field == null ? 0 : o.Field) > 0
select o

will result in TSQL containing a CASE statement:

SELECT [t0].[Field]
FROM [Table] AS [t0]
WHERE (
    (CASE
        WHEN [t0].[Field] IS NULL THEN 0
        ELSE [t0].[Amount]
     END)) > 0

But, can LINQ to SQL be coerced into generating TSQL code that contains ISNULL like the following?

SELECT [t0].[Field]
FROM [Table] AS [t0]
WHERE (ISNULL([t0].[Field],0)) > 0

I'm betting the answer is "no, it can't," but I'd like to see something authoritative.

like image 359
arcain Avatar asked Oct 07 '22 12:10

arcain


2 Answers

The only way I know of accomplishing this is via your own class like so:

public partial class LocalTestDataContext
{
    [Function(Name = "IsNull", IsComposable = true)]
    [return: Parameter(DbType = "NVarChar(MAX)")]
    public string IsNull(
        [Parameter(Name = "field", DbType = "NVarChar(MAX)")] string field,
        [Parameter(Name = "output", DbType = "NVarChar(MAX)")] string output)
    {
        return ((string)(this.ExecuteMethodCall(this,
                ((MethodInfo)(MethodInfo.GetCurrentMethod())),
                field, output).ReturnValue));
    }
}

This is under "Take #3" from here.

var ctx = new LocalTest.LocalTestDataContext(); 

var query = from c in ctx.Categories 
orderby ctx.IsNull(c.Description1, "") + ctx.IsNull(c.Description2, "") 
select c; 
query.Dump();

And will generate T-SQL with ISNULL().

like image 199
artofsql Avatar answered Oct 12 '22 13:10

artofsql


I always considered ISNULL and COALESCE to be equivalent, except for the number of possible parameters.

Just found that there are differences, though, so the question is: do these differences matter to you?

like image 36
devio Avatar answered Oct 12 '22 11:10

devio