使用Entity Framework存储库返回多个结果集

时间:2014-08-21 13:54:35

标签: entity-framework repository multiple-resultsets

我正在处理一个代码,我需要多个表作为存储过程的结果。我正在使用Entity Framework存储库模式。它返回并绑定一个IEnumerable对象,但我需要同时将它与多个IEnumerables绑定。 有人可以帮忙吗?

这是我正在使用的代码: db.Database.SqlQuery( “procReturnsMultipleResuiltSets”)

1 个答案:

答案 0 :(得分:1)

article中披露了实现目标的方法。

从相关文章中,最常见的方式是:

using (var db = new BloggingContext()) 
{ 
// If using Code First we need to make sure the model is built before we open the connection 
// This isn't required for models created with the EF Designer 
db.Database.Initialize(force: false); 

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

try 
{ 

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

    // Read Blogs from the first result set 
    var blogs = ((IObjectContextAdapter)db) 
        .ObjectContext 
        .Translate<Blog>(reader, "Blogs", MergeOption.AppendOnly);    


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

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


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

请注意重要说明:在转到下一个结果集之前必须先消耗第一个结果集