如何:执行返回嵌套集合的查询 (EntityClient)

这些内容演示如何使用 EntityCommand 对象针对概念模型执行命令,以及如何使用 EntityDataReader 检索嵌套集合结果。

运行本示例中的代码

  1. AdventureWorks 销售模型添加到您的项目并将项目配置为使用实体框架。 有关更多信息,请参见如何:使用实体数据模型向导(实体框架)

  2. 在应用程序的代码页中,添加以下 using 语句(在 Visual Basic 中为 Imports):

    using System;
    using System.Collections.Generic;
    using System.Collections;
    using System.Data.Common;
    using System.Data;
    using System.IO;
    using System.Data.SqlClient;
    using System.Data.EntityClient;
    using System.Data.Metadata.Edm;
    
    

示例

嵌套集合是指位于另一个集合内的集合。 以下代码检索 Contacts 的集合以及与每个 Contact 关联的 SalesOrderHeaders 的嵌套集合。

using (EntityConnection conn =
    new EntityConnection("name=AdventureWorksEntities"))
{
    conn.Open();
    // Create an EntityCommand.
    using (EntityCommand cmd = conn.CreateCommand())
    {
        // Create a nested query.
        string esqlQuery =
            @"Select c.ContactID, c.SalesOrderHeaders
        From AdventureWorksEntities.Contacts as c";

        cmd.CommandText = esqlQuery;
        // Execute the command.
        using (EntityDataReader rdr =
            cmd.ExecuteReader(CommandBehavior.SequentialAccess))
        {
            // The result returned by this query contains 
            // ContactID and a nested collection of SalesOrderHeader items.
            // associated with this Contact.
            while (rdr.Read())
            {
                // the first column contains Contact ID.
                Console.WriteLine("Contact ID: {0}", rdr["ContactID"]);

                // The second column contains a collection of SalesOrderHeader 
                // items associated with the Contact.
                DbDataReader nestedReader = rdr.GetDataReader(1);
                while (nestedReader.Read())
                {
                    Console.WriteLine("   SalesOrderID: {0} ", nestedReader["SalesOrderID"]);
                    Console.WriteLine("   OrderDate: {0} ", nestedReader["OrderDate"]);
                }
            }
        }
    }
    conn.Close();
}

另请参见

posted @ 2011-12-04 11:07  therockthe  阅读(342)  评论(0编辑  收藏  举报