Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a stored procedure from MVC with LINQ without specifying class structure (because its a pivot with dtynamic columns)

Tags:

asp.net-mvc

Is there any way to call a stored procedure with a dynamic result set (no of columns) without knowing the exact class model and having to define it up front. Just want to get a dynamic list then loop the rows?

As far as I know I cannot find any examples and not sure this is even possible but would be neat if I could do this...

    var query = _db.Database.SqlQuery<????>("EXEC [dbo].[PivotOnMeterReadView]");
    var result = query.ToList();
like image 904
John Avatar asked Nov 09 '22 12:11

John


1 Answers

As far as I know, it is not possible to execute a Stored Procedure via LINQ. You'll have to use SqlConnection and SqlCommand. Below is a code snippet which I have used for successful execution of a SP. Hope I could help :)

private readonly string sqlConnectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(sqlConnectionString); //sqlConnectionString is the database connection.
sqlconn.Open();
using (SqlCommand cmd = new SqlCommand("InsertUsers", sqlconn)) // "InsertUsers" is the name of SP.
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@User", SqlDbType.Structured).Value = User; //Here I am passing the "User" variable as an argument to the "@User" paramter
    cmd.ExecuteNonQuery();
}
sqlconn.Close();
like image 184
Abdul Samad Avatar answered Nov 15 '22 07:11

Abdul Samad