1

I couldn't find an answer to this. I'm sure the answer is simple, I don't think I was searching for the right thing.

I have a .dbml file with two tables: Employees and Departments. There's a relationship between the two, Employees has a DepartmentID.

Anyways, I'm doing this in my code:

Employee emp = Employee.Get(123);

string fname = emp.FirstName;
string lname = emp.LastName;
string deptName = emp.Department.Name;
string deptCode = emp.Department.Code;

What I'm wondering is, every time I call emp.Department, is that making a database call? Or was all that information loaded when I created the Employee object?

Steven
  • 18,761
  • 70
  • 194
  • 296
  • There is no way to know given what you have showed us. Please show the code for Employee.Get and Empoyee.Department -- then we can tell. – Hogan May 13 '11 at 18:00
  • 3
    imho, that the kind of things you should/could test by yourself. There are multiple ways to verify this : 1- use LinqPad, 2- put a trace on the SQL server, 3- break after your Get, before your fname = emp..., then change the value in the database or disable your network connection, 4- use the "go to definition" feature of VS on "FirstName" and dig a bit to see if it ever calls the DB. – Tipx May 13 '11 at 18:01

2 Answers2

4

It made a trip to database, when you first accessed emp.Department.Name unless deferred loading is turned off.

It won't make another trip when you say emp.Department.Code in next statement, it would have already got the Deparment object in memory.

This answer explains it in more detail.

You may want to see

Community
  • 1
  • 1
YetAnotherUser
  • 9,156
  • 3
  • 39
  • 53
  • Did it make another one when I said `emp.Department.Code`? – Steven May 13 '11 at 18:00
  • 1
    @Steven - I've modified my answer to answer your comment, and provide more details. Hope this helps. – YetAnotherUser May 13 '11 at 18:05
  • 1
    @Steven: NO! Once L2S has loaded the dependent entity - it's loaded and ready to be used; no need to go back to the database again - and L2s won't do that. It will load the dependent entity **once**, when you first access any of its properties - once that's done - it's done. – marc_s May 13 '11 at 18:28
0

The query is only executed once to retrieve data. After that it is tracked within the context in memory.

You could verify this using SQL Profiler.

Yuck
  • 49,664
  • 13
  • 105
  • 135