Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning says Linq-To-Sql Expression is always false, but this is incorrect, why?

I am getting a warning on the line noted in the comment in the code below. I am using Visual Studio 2015. I have 2 tables in a database, and querying them using Linq-2-Sql. The Linq Code performs a left join between the two tables on the companyID.

When run, the left join runs as expected, and I get all the values in TestTable1, but only records in TestTable2 where the companyIds match.

If the warning below were correct and the expression were always false, then the string "NULL" would never be assigned to value1. This is not the case, as when I run this I get "NULL" exactly when would be expected when doing a Left Join.

I use this pattern in many places in my code, and these warnings are everywhere, yet my code works fine with the NULL check I'm doing. The warning seems wrong to me. Am I missing something here?

t2.CompanyId is a database field of type INT. and also an int datatype in the linq-2-sql class, but somehow is still assigned null within the query.

    var db = new SandBoxDataContext();

    var result = (from t1 in db.TestTable1s

                  from t2 in db.TestTable2s
                    .Where(x => x.CompanyId == t1.CompanyId)
                    .DefaultIfEmpty()

                  select new
                  {
                      //t2.CompanyId == null in line below is underlined with the warning!
                      value1 = t2.CompanyId == null ? "NULL" : "INT"

                  }).ToList();

    foreach (var rec in result)
    {
        Response.Write("value1 = " + rec.value1 + "<br>");
    }

Here is the warning

CS0472  The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'

Below is the generated SQL

SELECT 
    (CASE 
        WHEN ([t1].[CompanyId]) IS NULL THEN 'NULL'
        ELSE CONVERT(NVarChar(4),'INT')
     END) AS [value1]
FROM [dbo].[TestTable1] AS [t0]
LEFT OUTER JOIN [dbo].[TestTable2] AS [t1] ON [t1].[CompanyId] = [t0].[CompanyId]
like image 612
Matthew Eskolin Avatar asked Oct 18 '22 13:10

Matthew Eskolin


1 Answers

The warning is because comparing any int expression with null is always false.

This can be different in query expressions. The provider can translate to whatever it likes. Apparently, the C# compiler chooses to still warn you although this is a query.

I do not know what L2S translates this to. You state that it works so apparently the translation does what you want and the warning is a false positive.

I suggest you rewrite this to a form that makes the warning go away and increases code intuitiveness in the process:

value1 = t2 == null ? "NULL" : "INT"
like image 135
usr Avatar answered Oct 21 '22 06:10

usr