Table-valued parameter in stored procedure - sql-server

It is my understanding that there is no elegant way to call a stored procedure in EF6 using table-valued parameters. Can someone verify or discredit my suspicion?
Table-valued type:
CREATE TYPE MyTestType AS TABLE
(
ID INT,
String VARCHAR(30)
);
Stored procedure:
CREATE PROCEDURE MyTestProc
#TestVar MyTestType READONLY
AS
BEGIN
SELECT * FROM #TestVar
END
C# EF call:
var testTable = new DataTable();
testTable.Columns.Add("ID", typeof (int));
testTable.Columns.Add("string", typeof (string));
testTable.Rows.Add(1, "Row1");
var parameter = new SqlParameter("#TestVar", SqlDbType.Structured);
parameter.Value = testTable;
parameter.TypeName = "dbo.MyTestType";
var results = dbContext.Database.SqlQuery<TestObject>("exec dbo.MyTestProc #TestVar", parameter).ToList();
The code above is working, I would just like to see if there is a more elegant way of executing it. I feel like I should be allowed to do something like
var results = dbContext.MyTestProc(testTable).ToList();
Edit
I came across this article which has a slightly cleaner way of handling the data table, but still hoping for a cleaner way to call my stored procedure with the table-valued parameter.
Code.msdn - Stored Procedure with Table-Valued Parameter in EF and ASP.NET MVC

Related

Run stored procedure to populate an existing table from an MVC Controller

The following SQL code works perfectly in [QTY] database. it deletes all the rows in [Table1], then runs the stored procedure [test] and inserts the result into [Table1].
I want to be able to run this code from an MVC controller. How can I achieve this? Thank you.
USE [QTY]
GO
DECLARE #return_value int
Delete from Table1
INSERT INTO Table1
EXEC #return_value = [dbo].[test]
#Month = N'M4',
#Forecast = '2019-04-30'
SELECT 'Return Value' = #return_value
GO
Try to use FromSql method which enables you to pass in a SQL command to be executed against the database to return instances of the type represented by the DbSet .
// Format string
var author = db.Authors.FromSql("SELECT * From Authors Where AuthorId = {0}", id).FirstOrDefault();
// String interpolation
var author = db.Authors.FromSql($"SELECT * From Authors Where AuthorId = {id}").FirstOrDefault();
The DbContext exposes a Database property which includes a method called ExecuteSqlCommand. This method returns an integer specifying the number of rows affected by the SQL statement passed to it.
using(var context = new SampleContext())
{
var commandText = "INSERT Categories (CategoryName) VALUES (#CategoryName)";
var name = new SqlParameter("#CategoryName", "Test");
context.Database.ExecuteSqlCommand(commandText, name);
}
You could take some time on the tutorial Executing Raw SQL Queries

How to call stored procedure with input, sql type and output parameters from Entity Framework 6

I am trying to execute a stored procedure that has input, sql type and output parameters using Entity Framework 6.1. If anyone has an idea how to do this, kindly let me know.
My stored procedure is like:
CREATE PROCEDURE procName
#usrid bigint,
#grpTyp tinyint,
#members typGrpMembers readonly,
#n int output
as
begin
--SQL COMMAND
end
Right click on project Add-> New Item
Choose Data tab and ADO.NET Entity Data Model
Next->Create new connection->Next->Next->Expand Stored Procs and check your proc. Check Import selected stored proc...->Finish
Save
Usage:
var context = new ..Entities();
var result = context.spYourProc(params).ToList();
For output type parameters do the following:
var param = new ObjectParameter("spParamName", typeof(int));
var context = new ..Entities();
var result = context.spYourProc(param).ToList();
var outputResult = int.Parse(param.Value.ToString());

Calling a sql server stored procedure with output parameter when using Simple.Data

Using Simple.Data, I would like to get the result from an output parameter in a stored procedure. Let's say I have the following SP (disregard the uselessness of it):
CREATE PROCEDURE [dbo].[TestProc]
#InParam int,
#OutParam int OUTPUT
AS
BEGIN
SELECT #OutParam = #InParam * 10
END
When I call it with Simple.Data, I use the following code.
var db = Database.Open();
int outParam;
var result = db.TestProc(42, out outParam);
Console.WriteLine(outParam); // <-- == 0
Console.WriteLine(result.OutputValues["OutParam"]); // <-- == 420
It feels like outParam should contain the value, and not the OutputValues dictionary. So my question is: Is there a nicer way to get the result from OutParam in this particular case?
Unfortunately, out parameters are not supported by the dynamic binding infrastructure used by Simple.Data, as they are not supported in all CLR languages.
I am open to suggestions for better syntax, though.

Entity Framework and Stored PRocedures, how to remove Nullable paremeters

Well I've been using Model-First with DbSet code generation. And now I what I want to do is to add some stored procedures.
But Code I get look like like:
public virtual ObjectResult<Nullable<int>> CountPostsInThread(Nullable<int> threadID, ObjectParameter postCount)
{
var threadIDParameter = threadID.HasValue ?
new ObjectParameter("threadID", threadID) :
new ObjectParameter("threadID", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Nullable<int>>("CountPostsInThread", threadIDParameter, postCount);
}
Now, how Do I get rid off all those ?
It's something wrong with tt files, or with my stored procedure ?
SP:
ALTER PROCEDURE dbo.sp_CountPostsInThread
(
#threadID int,
#PostCount int = 0 OUTPUT
)
AS
SELECT COUNT(*)
FROM PostSet
WHERE PostSet.ThreadID = #threadID
Nothing is wrong with the template or stored procedure. SP's parameters accept NULL value so because of that EF makes them nullable. The ternary operator is used because if you pass null EF must somehow pass the type of null parameter to correctly setup SqlParameter used internally.

Subsonic 3 - Passing null value to stored procedure parameter

Using Subsonic 3.0.0.3 is it feasible to pass a null value to a stored procedures parameter? If so, what is the appropriate way?
Details
Say I have an sp where one of the parameters has a default value like:
CREATE Procedure Test_SPWithNullParams( #p1 int=null, #p2 varchar(50) )
AS
SELECT 1 as Stuff
Then in my code I want to do something like:
var db = new Sandbox.DB();
StoredProcedure sproc = db.Test_SPWithNullParams( null , "test");
//alternately --> db.Test_SPWithNullParams("test");
The way the corresponding function generated in StoredProcedures.cs, however, the parameter for #p1 is not nullable. So what are my alternatives? I came across this article (http://brianmrush.wordpress.com/2010/01/19/subsonic-t4-templates-stored-procedures-nullable-parameters) but it seems like a cumbersome work around that effectively branches the code base.
Alternatively I've thought about manually overriding the command object. Something like:
int dummyInt = -1;
StoredProcedure sproc = db.Test_SPWithNullParams( dummyInt , "test");
sproc.Command.Parameters[0].ParameterValue = DBNull.Value;
Thoughts?
I don't have Subsonic at hand, but perhaps you could use nullable int.
int? dummyInt = null;
StoredProcedure sproc = db.Test_SPWithNullParams( dummyInt , "test");
No way. Stored procedures are generated only with no nullable types. Why not try something like this?:
StoredProcedure sproc = db.Test_SPWithNullParams( someNullableInt.HasValue ? someNullableInt.Value: 0, "test");

Resources