Skip to content

Instantly share code, notes, and snippets.

@ScottGuymer
Created May 28, 2013 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ScottGuymer/5663359 to your computer and use it in GitHub Desktop.
Save ScottGuymer/5663359 to your computer and use it in GitHub Desktop.
Accessing a SQL Stored procedure with multiple result sets using Entity Framework
using (var db = new BloggingContext())
{
// Create a SQL command to execute the sproc
var cmd = db.Database.Connection.CreateCommand();
cmd.CommandText = "[dbo].[uspCustomerAndCompanySearch] @Query";
// Add Parameters to cmd here
cmd.Parameters.Add(new SqlParameter("query", response.Query));
try
{
((IObjectContextAdapter)db).ObjectContext.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
{
((IObjectContextAdapter)db).ObjectContext.Connection.Close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment