使用EntityFramework仓库返回多个结果集 [英] Returning multiple resultsets with EntityFramework repository

查看:470
本文介绍了使用EntityFramework仓库返回多个结果集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on a code where I need Multiple tables as result of a stored procedure. I am using Entity Framework repository pattern. It returns and bind an IEnumerable object, but I need to bind it with multiple IEnumerables at the same time. Can anybody help?

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

This is the code I am using : db.Database.SqlQuery("procReturnsMultipleResuiltSets")

推荐答案

文章

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

From related article the most common way is:

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

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

please note the important remark: The first result set must be consumed before moving to the next result set.

这篇关于使用EntityFramework仓库返回多个结果集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆