Returning multiple resultsets with EntityFramework repository

ぃ、小莉子 提交于 2019-12-17 19:58:11

问题


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?

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


回答1:


the ways to achieve your goal are disclosed in this article.

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.



来源:https://stackoverflow.com/questions/25428202/returning-multiple-resultsets-with-entityframework-repository

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!