The warning says that the Linq-To-Sql expression is always incorrect, but it is not, why?

I get a warning in the line indicated in the comment in the code below. I am using Visual Studio 2015. I have 2 tables in the database and query them using Linq-2-Sql. The Linq code performs a left join between two tables on the company identifier.

When starting up, the left connection is executed as expected, and I get all the values ​​in TestTable1, but only the entries in TestTable2, where the companyIds data matches.

If the warning below was correct and the expression was always false, then the string "NULL" would never be assigned to value1. This is not so, because when I run this, I get "NULL" exactly when you would expect when you will be a left join.

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

t2.CompanyId is a database field of type INT. as well as the int data type in the linq-2-sql class, but somehow it is still set to null in 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 a 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]
+4
source share
1 answer

The warning is that comparing any expression intwith nullalways false.

. , . -, # , .

, L2S . , , , , , .

, :

value1 = t2 == null ? "NULL" : "INT"
+3

All Articles