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

Viewed 826

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]
1 Answers
Related