Stored Procedure with SimpleRepository - stored-procedures

How to I execute a Stored Procedure with SimpleRepository and get a Typed List as a answer?
I'm using SubSonic 3.
Thanks.

Found my answer:
StoredProcedure sproc = new StoredProcedure("SprocName", ProviderFactory.GetProvider(ConnectionStringName));
string input= "input text";
sproc.Command.AddParameter("input", input, DbType.String);
return sproc.ExecuteTypedList<T>();

Related

Stored procedure "weird" result set with Power Tools EF Core 5

I have installed EF Core 5 Power Tools to Add a DB with stored procedure to an ASP.NET Core project. the models are successfully generated by Power Tools and the tables work fine; but when i try to retrieve a result set out of a stored procedure and store it to a ViewBag to display on the View, the value stored at Viewbag is weird and has nothing to do with a result set.
Here is the stored procedure code at db, which is pretty simple, just to test Power Tools:
CREATE PROCEDURE retTable (#P INT)
AS
BEGIN
SELECT * FROM STU WHERE ID=#P;
END;
Controller:
public IActionResult Index()
{
schoolContext s = new schoolContext();
schoolContextProcedures sp = new schoolContextProcedures(s);
var t = sp.retTableAsync(20); // The built is perfectly done, but the value store instead of result set is weird
ViewBag.test = t;
return View();
}
and just added a #View.Bag to the view to make sure it's displayed, Though the app's built is done successfully without any error, This is what's displayed at the View instead of ViewBag value:
System.Runtime.CompilerServices.AsyncTaskMethodBuilder1+AsyncStateMachineBox1[System.Collections.Generic.List`1[WebApplication2.Models.DB.retTableResult],WebApplication2.Models.DB.schoolContextProcedures+d__3]
Tried to convert the result set to a list or something else but it's not working :|
Anyone know how to fix it?
The value stored in it is not "weird", its a Task.
Since your method is async, you should await for the result of the returned task, not the "return" itself, as this is only a reference to the task that is executed asynchronusly.
As martin smith mentions, just:
var t = await sp.retTableAsync(20);
Otherwise you are adding a task as the viewbag property, instead of the task result once completed

Stored procedure returning dynamic columns in Entity Framework

I have a function calling a SQL Server stored procedure using Entity Framework 6.2.
The stored procedure returns a result set which has different number of columns on each call, and column names may vary on each call.
Function getListOfDocs() As JsonResult
Try
Using entities As PromatEntities = New PromatEntities()
Dim param(1) As SqlParameter
param(0) = New SqlParameter("#ProjID", SqlDbType.Int)
param(0).Value = vProjectId
Dim query = entities.Database.SqlQuery(Of "help required here")("sp_EIP_IPSSDocMaster_Get", param) // cannot handle this case as entity framework needs type
Dim lstDocs = query.ToList
End Using
Return Json(New With {lstDocs}, JsonRequestBehavior.AllowGet)
Catch ex As Exception
ClsCommon.ExceptionManager(ex)
Return Nothing
End Try
End Function
But Entity Framework doesn't allow anonymous types in database.SqlQuery. Can anyone suggest a way to solve the issue and get the anonymous type data to view?

Conversion failed because the DateTime data value overflowed the type specified for the DateTime value part in the consumer's buffer

i have a stored procedure in Sybase ASE with date params in it, so when i created a OLE DB Connection and passing the date parameters to the OLE DB Command,And we are mapping to the parameter with OLEDBType.DBTimeStamp type, datetime param type in stored procedure is smalldatetime.
Here is the sample code.
OLEDBConnection con = new OLEDBConnection(connectionstring);
con.open;
OLEDBCommand cmd = new OLEDBCommand(con);
cmd.QueryString = "dbo.job_xb_new"
cmd.QueryType = "Stored Procedure";
cmd.Parameters.Add("#signoff",OLEType.DBTimeStamp);
cmd.Parameters("#signoff").Value = Datetime.now;
cmd.executeNonQuery(); -----------> ERROR HERE
while executing the store-procedure i am receiving the error.
"Conversion failed because the DateTime data value overflowed the type specified for the DateTime value part in the consumer's buffer" ?
Please help!!!
With the only information given there may be a solution to try.
Change the datatype of your input value to the stored proc to a char/varchar
create procedure dbo.myProc
#inDate varchar(20)
AS
BEGIN
..
END
Perform internal conversion from that with CONVERT before passing to your query.
SET #inDate = CONVERT(datetime,#inDate,[style parameter number])
For troubleshooting, just comment out everything in the procedure and SELECT #inDate first to determine what the data coming in from the OLE DB app looks like. You may be in for a surprise there...

Stored Procedure with Entity Framework

I have one Stored Procedure with different actions in it. For Eg - Insert, select, update all are in one stored procedure and I execute it using a if else condition.
BEGIN
if(#type = 'add')
INSERT INTO [dbo].[napme]
([firstname]
,[lastname]
,[Address]
,[City])
VALUES
(#firstname,#lastname,#Address,#City)
if(#type = 'select')
select * from napme
END
Now can I use that procedure in MVC using Entity Framework. If so how?
Once such method is mapping the parameters but I am unable to map #type
Can anyone suggest any easy way
You can try like this
var courseList = ctx.Database.SqlQuery<YourEntityName>("exec ProcName #Param1", Param1).ToList<YourEntityName>();
If you plan on using Code-First EntityFramework then you can map Insert, Update and Delete operations to stored procedures if you wish.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder
.Entity<YourEntityClass>()
.MapToStoredProcedures();
}
With a SP example like so:
CREATE PROCEDURE [dbo].[YourEntityClass_Insert]
#param1 nvarchar(max),
#param2 nvarchar(max)
AS
BEGIN
INSERT INTO [dbo].[YourEntityClass] ([col1], [col2])
VALUES (#param1, #param2)
Look here for more information.
If you plan on executing a SP for other reasons (non CRUD) then you will have to execute a SP as per bharats answer.

How to execute SubSonic3 StoredProcedure with return value

How do I execute a SP and get the return value. The below code always returns null object. The storedprocedure has been tested in the database using the same parameters as in code, but the SubSonic sp always returns null. When executed in the db via sql, it returns the correct values.
This is using SubSonic 3.0.0.3.
myDB db = new myDB();
StoredProcedure sp = db.GetReturnValue(myParameterValue);
sp.Execute();
int? myReturnValue = (int?)sp.Output;
In the above code, sp.Output is always null. When executed in the database, the returned variable is a valid integer (0 or higher) and is never null.
Stored procedure code below:
CREATE PROCEDURE [dbo].[GetReturnValue]
#myVariable varchar(50)
AS
declare #myReturn int
BEGIN
set #myReturn = 5;
return #myReturn;
END
When executing the stored proc in SQL Server, the returned value is '5'.
I copied your sproc and stepped through the SubSonic code and .Output is never set anywhere. A work around would be using an output parameter and referring to it after executing: sproc.OutputValues[0];
Here's a simple way to do it:
In the stored procedure, instead of using RETURN, use SELECT like this:
SELECT ##ROWCOUNT
or
SELECT #TheIntegerIWantToReturn
Then in the code use:
StoredProcName.ExecuteScalar()
This will return the single integer you SELECTED in your stored procedure.
CREATE PROCEDURE [dbo].[GetReturnValue]
#myVariable varchar(50)
#myReturn BIGINT OUTPUT
AS
declare #myReturn int
BEGIN
set #myReturn = 5;
return #myReturn;
END

Resources