zoukankan      html  css  js  c++  java
  • LINQ to Entities 常用查询语句

    要使用关联实体返回局部或完整的对象图,需要在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);
    
    
  • 相关阅读:
    Datediff的使用(统计本日,昨日,本周,本月)
    数据库之查询语句
    数据库之表关系
    数据库中的数据类型
    数据库概念和基本操作
    IO模型
    并发编程之协程
    GIL与多线程(线程池与进程池,同步异步阻塞非阻塞)
    并发编程之多线程
    并发编程之多进程
  • 原文地址:https://www.cnblogs.com/kongbin/p/3197509.html
Copyright © 2011-2022 走看看