• LINQ to Entities,基于方法查询,查询表达式语法


    初次学习LINQ to Entities,给出两种查询的示例代码。

    基于方法的查询:

    using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
    {
        ObjectSet<Contact> contacts = AWEntities.Contacts;
        ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;

        var query =
        contacts.SelectMany(
            contact => orders.Where(order =>
                (contact.ContactID == order.Contact.ContactID)
                    && order.OrderDate >= new DateTime(2002, 10, 1))
                .Select(order => new
                {
                    ContactID = contact.ContactID,
                    LastName = contact.LastName,
                    FirstName = contact.FirstName,
                    OrderID = order.SalesOrderID,
                    OrderDate = order.OrderDate
                }));

        foreach (var order in query)
        {
            Console.WriteLine("Contact ID: {0} Name: {1}, {2} Order ID: {3} Order date: {4:d} ",
                order.ContactID, order.LastName, order.FirstName,
                order.OrderID, order.OrderDate);
        }
    }

    查询表达式:

    using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
    {
        ObjectSet<Contact> contacts = AWEntities.Contacts;
        ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;

        var query =
            from contact in contacts
            from order in orders
            let total = order.TotalDue
            where contact.ContactID == order.Contact.ContactID
                && total >= 10000.0M
            select new
            {
                ContactID = contact.ContactID,
                LastName = contact.LastName,
                OrderID = order.SalesOrderID,
                total
            };

        foreach (var order in query)
        {
            Console.WriteLine("Contact ID: {0} Last name: {1} Order ID: {2} Total: {3}",
                order.ContactID, order.LastName, order.OrderID, order.total);
        }
    }

  • 相关阅读:
    特性标签的灵活使用
    算法实例题
    网络抓包工具
    vs2010
    .NET Remoting vs Web Service
    电子商务网站设计学习
    EXCEL导出
    C# 16进制与字符串、字节数组之间的转换
    DES加密
    DataGridView生成CSV,XML 和 EXCEL文件
  • 原文地址:https://www.cnblogs.com/jazzdan/p/2006354.html
Copyright © 2020-2023  润新知