Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query ToList() returns null

Class

public class Employee
{
    public string EmployeeID { get; set; }
    public string Surname { get; set; }
    public string FirstName { get; set; }
    public bool Employed { get; set; }
    public bool Administrator { get; set; }
}

Linq statement

var adminlist = db.Employees.Where(x => x.Administrator).Select(x => x.Administrator).ToList();

I'm sure this is a stupid question but please can anybody tell me why the above returns null? I've tried this too:

var adminlist = db.Employees.Where(x => x.Administrator).ToList();
like image 757
user1405195 Avatar asked May 03 '13 18:05

user1405195


People also ask

Does ToList ever return null?

If you have a Query that returns a empty set then ToList returns null. You would probably expect it to return an empty list (Count = 0), which is the case when using data providers for SQL Server.

Does LINQ query return null?

It will return an empty enumerable. It won't be null.

What does LINQ query return?

By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.


1 Answers

Your second query will NEVER return null unless the database is inaccessible. IEnumerable.ToList() will never return null, only an empty list if no items were found. It will throw an exception if the source is null.

Your problem lies elsewhere.

like image 171
gunr2171 Avatar answered Oct 14 '22 20:10

gunr2171