EF4使用多个结果集调用存储过程

时间:2013-11-20 11:59:44

标签: c# entity-framework-4

我有返回多个结果集的存储过程。我想使用EF4执行该SP并获取所有结果集数据。

1 个答案:

答案 0 :(得分:0)

请尝试以下代码:

using (var db = new customerContext())
{

    // Create a SQL command to execute the stored procedure
    var cmd = db.Database.Connection.CreateCommand();
    cmd.CommandText = "[dbo].[GetAllCustomerAndOrders]";

    try
    {

        db.Database.Connection.Open();
        // Run the stored procedure
        var reader = cmd.ExecuteReader();

        // Read customer from the first result set
        var customers = ((IObjectContextAdapter)db)
            .ObjectContext
            .Translate<Customer>(reader, "Customers", MergeOption.AppendOnly);   


        foreach (var item in customers) 
        {
            Console.WriteLine(item.Name);
        }        

        // Move to second result set and read orders
        reader.NextResult();
        var orders = ((IObjectContextAdapter)db)
            .ObjectContext
            .Translate<Order>(reader, "Orders", MergeOption.AppendOnly);


        foreach (var item in orders)
        {
            Console.WriteLine(item.OrderNumber);
        }
    }
    finally
    {
        db.Database.Connection.Close();
    }
}