简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM