at what point does linq-to-sql or linq send a requ

2020-07-26 19:56发布

问题:

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?

回答1:

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.



回答2:

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.