Created
September 27, 2018 20:35
-
-
Save ti-ka/82b8b6aa2e9d4ddb0c55fb649eff1f1a to your computer and use it in GitHub Desktop.
DbContextEntensions for Stored Procedure in Entity Framework Core
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 System.Collections.Generic; | |
using System.Data; | |
using Microsoft.EntityFrameworkCore; | |
namespace RasuwaProfile.Repository.Extensions | |
{ | |
public static class DbContextEntensions | |
{ | |
public static IEnumerable<Dictionary<string, object>> FromDynamicStoredProc(this DbContext dbContext, string name, Dictionary<string, object> parameters = null) | |
{ | |
var results = new List<Dictionary<string, object>>(); | |
var dbConnection = dbContext.Database.GetDbConnection(); | |
using (var command = dbConnection.CreateCommand()) | |
{ | |
command.CommandText = name; | |
command.CommandType = CommandType.StoredProcedure; | |
if (parameters != null) | |
{ | |
foreach (var key in parameters.Keys) | |
{ | |
var parameter = command.CreateParameter(); | |
parameter.ParameterName = "@" + key; | |
parameter.Value = parameters[key]; | |
command.Parameters.Add(parameter); | |
} | |
} | |
dbContext.Database.OpenConnection(); | |
using (var reader = command.ExecuteReader()) | |
while (reader.Read()) | |
{ | |
var row = new Dictionary<string, object>(); | |
for (var i = 0; i < reader.FieldCount; i++) | |
row[reader.GetName(i)] = reader.GetValue(i); | |
results.Add(row); | |
} | |
} | |
return results; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment