Question

I'm trying to understand why the query below fails with

System.NullReferenceException: Object reference not set to an instance of an object.

            var query = from p in  UserProfiles.ToList()
                    where p.FirstName.ToLower().Contains(lettersToMatch.ToLower()) || p.LastName.ToLower().Contains(lettersToMatch.ToLower()) 
                    select new MembershipSummaryDTO
                    {
                        EmailAddress = p.EmailAddress,
                        FullName = string.Format("{0} {1}", p.FirstName, p.LastName),
                        UserName = p.UserName,
                        IsApproved = p.IsEnabled,
                        UserId = p.UserId
                    };

The stack trace points to the WHERE clause

Line 133: where p.FirstName.ToLower().Contains(lettersToMatch.ToLower()) || p.LastName.ToLower().Contains(lettersToMatch.ToLower())

The fix is to remove the .ToList() on the UserProfiles.ToList() , I would like to understand why this fails (without the fix in place).

Was it helpful?

Solution

One of the things before the . is null. Find out which.

The ToList causes most of the query to run as LINQ to Objects which has exactly C# semantics. Without ToList most runs in the database which has different semantics for NULL values.

Probably, you should both understand what is null and run the query in the database.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top