Brian Triplett
Brian Triplett

Reputation: 3532

LINQ to SQL obtaining data from tables not listed in a query

I'm using LINQ to SQL to obtain data from a set of tables in a SQL Server 2012 database. The results of the query are correct and have constructed my domain objects correctly; however, when I examine the generated SQL (either through DataContext.Log or SQLProfiler) the queries seem impossibly terse.

Most notably, many of my instances are being constructed by data from rows in one specific table. I'm accessing this table through foreign keys by tables that have a one-to-many relationship to said table, however, this table doesn't appear anywhere in the SQL queries! Not in FROM or JOIN statements or anything.

I'm certainly happy that the generated queries are performing correctly and quickly but I just don't understand how data is being obtained from a table not mentioned anywhere in the generated SQL. I'd like to understand what's going on.

Any ideas?

Upvotes: 3

Views: 126

Answers (1)

sloth
sloth

Reputation: 101042

This is probably due to Deferred Loading.

When loading your domain objects, depending domain objects are not loaded until you access them explicitly.

From MSDN:

When you query for an object, you actually retrieve only the object you requested. The related objects are not automatically fetched at the same time. ... You cannot see the fact that the related objects are not already loaded, because an attempt to access them produces a request that retrieves them.

Read more about deferred loading here and here.

Upvotes: 4

Related Questions