简体   繁体   English

Linq-To-Sql数据库调用

[英]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. 我有一个带有两个表的.dbml文件:Employees和Departments。 There's a relationship between the two, Employees has a DepartmentID. 两者之间存在关系,员工有一个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? 我想知道的是,每当我打电话给emp.Department ,是打电话给数据库吗? Or was all that information loaded when I created the Employee object? 或者在创建Employee对象时加载了所有信息?

It made a trip to database, when you first accessed emp.Department.Name unless deferred loading is turned off . 当您第一次访问emp.Department.Name时,它会访问数据库,除非关闭延迟加载

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. 当你在下一个语句中说emp.Department.Code时,它将不会再次出现,它已经在内存中获得了Deparment对象。

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. 您可以使用SQL事件探查器验证这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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