Skip to content

Instantly share code, notes, and snippets.

@demosdemon
Last active November 4, 2016 20:10
Show Gist options
  • Save demosdemon/b5e389832173eb57d9d0b6f3f939ad96 to your computer and use it in GitHub Desktop.
Save demosdemon/b5e389832173eb57d9d0b6f3f939ad96 to your computer and use it in GitHub Desktop.
EF6 Execute Stored procedure, automatic parameters
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Collections.Generic;
using System.Data.SqlClient;
public static class DbContextHelper
{
/// <summary>
/// Execute the stored procedure on the remote server
/// </summary>
/// <typeparam name="TReturn">The return type from <paramref name="method"/> </typeparam>
/// <param name="method">Either <see cref="Database.ExecuteSqlCommand(string, object[])"/>
/// or <see cref="Database.SqlQuery{TElement}(string, object[])"/> </param>
/// <param name="proc">The name of the stored procedure to execute</param>
/// <param name="parameters">The parameters to pass to the stored procedure</param>
/// <returns></returns>
public static TReturn Execute<TReturn>(Func<string, object[], TReturn> method, string proc, params object[] parameters)
{
var sqlParameters = parameters
.Select((param, idx) => new SqlParameter($"@p{idx}", param))
.ToArray();
var paramList = string.Join(", ", parameters.Select((p, idx) => $"@p{idx}"));
var query = $"{proc} {paramList}";
return method(query, sqlParameters);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment