Created
May 28, 2013 14:56
-
-
Save ScottGuymer/5663359 to your computer and use it in GitHub Desktop.
Accessing a SQL Stored procedure with multiple result sets using Entity Framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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