Steven
Steven

Reputation: 18859

Linq-To-Sql database calls

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?

Upvotes: 1

Views: 523

Answers (2)

YetAnotherUser
YetAnotherUser

Reputation: 9346

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

Upvotes: 4

Yuck
Yuck

Reputation: 50825

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.

Upvotes: 0

Related Questions