简体   繁体   中英

at what point does linq-to-sql or linq send a request to the database

I want to make my queries better but have been un-able to find a resource out there which lays out when a query is shipped of to the db.

DBContext db = new DBContext();
Order _order = (from o in db
                where o.OrderID == "qwerty-asdf-xcvb"
                select o).FirstOrDefault();
String _custName = _order.Customer.Name +" "+_order.Customer.Surname;

Does the assignment of _custName need to make any request to the database?

Does the assignment of _custName need to make any request to the database?

It depends on whether or not Order.Customer is lazily loaded. If it is lazily loaded, then yes. Otherwise, no.

By the way, you can investigate this easily if you set the DataContext.Log property:

db.Log = Console.Out;

Then you can watch the SQL statements on the console. By stepping through your program you can see exactly when the SQL statement hits the database.

Check out MSDN on Deferred versus Immediate Loading . In particular, you can turn off lazy loading . Watch out for the SELECT N + 1 problem .

Just FYI, besides lazy loading, there is another reason why database activity may not occur when you expect it to when using LINQ. For example, if I change your example code slightly:

DBContext db = new DBContext();
var orders = (from o in db
            where o.OrderID == "qwerty-asdf-xcvb"
            select o);
var order = orders.FirstOrDefault();
String _custName = _order.Customer.Name +" "+_order.Customer.Surname;

Someone unfamiliar with how LINQ works may expect that all orders are retrieved from the database when the second line of code is executed. In fact, LINQ delays querying the database until the last possible moment, which in this case is the call to FirstOrDefault. Of course, at this point LINQ knows to only retrieve at most one record.

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