Check LINQ query for null

I have userList, some users do not have a name (null). If I ran the first LINQ query, I got an error with the error message "object reference not installed on the object instance".

var temp = (from a in userList
            where ((a.name == "john") && (a.name != null))
            select a).ToList();

However, if I switch the order by setting the check to zero in front, then it works without any errors:

var temp = (from a in userList
            where ((a.name != null) && (a.name == "john"))
            select a).ToList();

Why? If this is pure C # code (not LINQ), I think both of them will be the same. I don’t have an SQL profiler, I’m just wondering what difference it makes when they are transferred to the SQL level.

+3
source share
2 answers

# && , , false, . MSDN:

-AND (& &) -AND bool, .

|| , , , true.


, . :

  • SQL DataContext.Log.
  • , , .
  • LINQ LINQ to SQL.
  • , .

SQL Visual Studio SQL. LINQ to SQL SQL. DataContext.Log SQL, , :

TextWriter textWriter = new StringWriter();
using (var dc = new UserDataContext())
{
    dc.Log = textWriter;
    var userList = dc.Users;
    var temp = (from a in userList
                where (a.Name.ToString() == "john") && (a.Name != null)
                select a).ToList();
}
string log = textWriter.ToString();

Console.Out:

dc.Log = Console.Out;

, , , , , :

SELECT [t0].[Name]
FROM [dbo].[User] AS [t0]
WHERE ([t0].[Name] = @p0) AND ([t0].[Name] IS NOT NULL)

, . a.name null, a == "john" , false.

, , # LINQ to SQL. . , - ToString a.name:

var temp = (from a in userList
            where (a.Name.ToString() == "john") && (a.Name != null)
            select a).ToList();

Linq NullReferenceException, LINQ to SQL . , . , , - :

var userList = dc.Users.ToList();

, :

var userList = dc.Users;

, , . , .

+10

, SQL, , SQL , SQL .

, LINQ:

where p.CategoryID != null && p.CategoryID.Value > 1
where p.CategoryID.Value > 1 && p.CategoryID != null

SQL:

WHERE ([t0].[CategoryID] IS NOT NULL) AND (([t0].[CategoryID]) > @p0)
WHERE (([t0].[CategoryID]) > @p0) AND ([t0].[CategoryID] IS NOT NULL)
0

Source: https://habr.com/ru/post/1745604/


All Articles