要使用关联实体返回局部或完整的对象图,需要在LINQ 标准查询操作符之前执行Include()操作符,如下列查询所示,它将返回和前面“使用Include()操作符进行预先加载”一节同样的结果:
- C#3.0
- using(NorthwindEntitiesocNwind=new
- NorthwindEntities("name=NorthwindEntities"))
- {
- List<Order>orderList=null;
- ObjectQuery<Order>orders=ocNwind.Orders;
- orders.MergeOption=MergeOptions.AppendOnly;
- varorderQuery=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(OrderorderinorderQuery)
- {
- //Materializetheobject
- orderList.Add(order);
- }
- }
- VB9.0
- UsingocNwindAsNewNorthwindEntities("name=NorthwindEntities")
- DimorderListAsList(OfOrder)=Nothing
- DimoqOrdersAsObjectQuery(OfOrder)=ocNwind.Orders
- orders.MergeOption=MergeOptions.AppendOnly
- DimorderQuery=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)
- ForEachoqOrderAsOrderInorderQuery
- 'Materializetheobject
- orderList.Add(oqOrder)
- NextoqOrder
- EndUsing
LINQ 表达式语法和串联方法调用区别较大。在4 个标准查询操作符执行之后,要将ObjectQuery<Order>改变为IQueryable<Order>类型,需要把Include()操作符和LINQ 表达式相分隔,如下所示:
- C#3.0
- ordersorders=orders.Include("Order_Details")
- .Include("Customer")
- .Include("Employee")
- .Include("Shipper");
- orderQuery=(fromoinorders
- whereo.Customer.Country=="Brazil"
- orderbyo.OrderIDdescending
- selecto).Take(5);
- VB9.0
- oqOrdersoqOrders=oqOrders.Include("Order_Details")
- .Include("Customer")
- .Include("Employee")
- .Include("Shipper")
- orderQuery=(FromoInoqOrders_
- Whereo.Customer.Country="Brazil"_
- OrderByo.OrderIDDescending_
- Selecto).Take(5)
可选地,可以使用下面这样更为易读的语法:
- C#3.0
- orderQuery=(fromoinorders.Include("Order_Details")
- .Include("Customer")
- .Include("Employee")
- .Include("Shipper")
- whereo.Customer.Country=="Brazil"
- orderbyo.OrderIDdescending
- selecto).Take(5);
- VB9.0
- orderQuery=(FromoInoqOrders.Include("Order_Details"_
- .Include("Customer")_
- .Include("Employee")_
- .Include("Shipper")_
- Whereo.Customer.Country="Brazil"_
- OrderByo.OrderIDDescending_
- selecto).Take(5);