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).

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top