Home > database >  C# ToList inside LINQ
C# ToList inside LINQ

Time:02-10

I'm working with LINQ and I wonder what's the difference between the two codes below. The result seems same but does using ToList() inside the query like student1 makes one more access to Database?

var students1 = (from stud in dbContext.Students.Where(s => s.LastName == "Doe").ToList()
               join class in dbContext.Classes
               on ...).ToList();

var students2 = (from stud in dbContext.Students.Where(s => s.LastName == "Doe")
               join class in dbContext.Classes
               on ...).ToList();

CodePudding user response:

ToList materializes the query. Note that when accessing the database you are working with IQueryable and your join and where clauses get passed to the database. If you materialize the queryable by calling ToList the database does not process the join but you join the inmemory data with LinqToObjects instead of with LinqToSql.

CodePudding user response:

LINQ to SQL is a facility for managing and accessing relational data as objects.

  1. It connects to a database, converts LINQ constructs into SQL
  2. submits the SQL
  3. transforms results into objects
  4. Even tracks changes and automatically requests database updates
  • Related