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);
    }
}

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

作者: 翟士丹 发表于 2011-04-06 09:24 原文链接

评论: 0 查看评论 发表评论


最新新闻:
· 来无影去无踪 黑客组织Lulzsec震撼互联网(2011-07-01 22:22)
· Facebook社交广告影响:扩大传统内容影响力(2011-07-01 22:19)
· Chrome浏览器全球市场份额6月份升至13.1%(2011-07-01 21:19)
· 微软Windows Phone 7应用突破25000个(2011-07-01 21:11)
· 传三大私募机构商谈惠普分拆PC业务可能性(2011-07-01 20:50)

编辑推荐:"No Backspace in Real Life" 博客园2011T恤正式发布

网站导航:博客园首页  我的园子  新闻  闪存  小组  博问  知识库

你可能感兴趣的:(LINQ)