要使用关联实体返回局部或完整的对象图,需要在LINQ 标准查询操作符之前执行Include()操作符,如下列查询所示,它将返回和前面“使用Include()操作符进行预先加载”一节同样的结果:
using (NorthwindEntities ocNwind = new NorthwindEntities("name=NorthwindEntities")) { List<Order> orderList = null; ObjectQuery<Order> orders = ocNwind.Orders; orders.MergeOption = MergeOptions.AppendOnly; var orderQuery = orders.Include("Order_Details") .Include("Customer") .Include("Employee") .Include("Shipper") .Where(o => o.Customer.Country == "Brazil") .OrderByDescending(o => o.OrderID) .Select(o => o) .Take(5); foreach (Order order in orderQuery) { // Materialize the object orderList.Add(order); } } VB 9.0 Using ocNwind As New NorthwindEntities("name=NorthwindEntities") Dim orderList As List(Of Order) = Nothing Dim oqOrders As ObjectQuery(Of Order) = ocNwind.Orders orders.MergeOption = MergeOptions.AppendOnly Dim orderQuery = oqOrders.Include("Order_Details") _ .Include("Customer") _ .Include("Employee") _ .Include("Shipper") _ .Where(Function(o) o.Customer.Country = "Brazil") _ .OrderByDescending(Function(o) o.OrderID) _ .Select(Function(o) o) _ .Take(5) For Each oqOrder As Order In orderQuery ' Materialize the object orderList.Add(oqOrder) Next oqOrder End Using
LINQ 表达式语法和串联方法调用区别较大。在4 个标准查询操作符执行之后,要将ObjectQuery<Order>改变为IQueryable<Order>类型,需要把Include()操作符和LINQ 表达式相分隔,如下所示:
ordersorders = orders.Include("Order_Details") .Include("Customer") .Include("Employee") .Include("Shipper"); orderQuery = (from o in orders where o.Customer.Country == "Brazil" orderby o.OrderID descending select o).Take(5); VB 9.0 oqOrdersoqOrders = oqOrders.Include("Order_Details") .Include("Customer") .Include("Employee") .Include("Shipper") orderQuery = (From o In oqOrders _ Where o.Customer.Country = "Brazil" _ Order By o.OrderID Descending _ Select o).Take(5)
可选地,可以使用下面这样更为易读的语法:
orderQuery = (from o in orders.Include("Order_Details") .Include("Customer") .Include("Employee") .Include("Shipper") where o.Customer.Country == "Brazil" orderby o.OrderID descending select o).Take(5); VB 9.0 orderQuery = (From o In oqOrders.Include("Order_Details" _ .Include("Customer") _ .Include("Employee") _ .Include("Shipper") _ Where o.Customer.Country = "Brazil" _ Order By o.OrderID Descending _ select o).Take(5);