Why is data not stored in database from stored procedure? - c#

I'm using Entity Framework and I'm trying to store some data in SQL Server using this stored procedure:
create procedure [dbo].[Sp_OrderList]
#OrderId int,
#OrderName varchar(50),
#OrderData datetime
As
Begin
Insert into OrderList (OrderId, OrderName, OrderDate)
values (#OrderId, #OrderName, #OrderData)
End
C# code:
public HttpResponseMessage SaveCountry(OrderList cnt)
{
OrderList Cntrcountr = new OrderList();
Cntrcountr.OrderId = cnt.OrderId;
Cntrcountr.OrderName = cnt.OrderName;
Cntrcountr.OrderDate = cnt.OrderDate;
var param = new SqlParameter("",Cntrcountr);
var country = db.Database.SqlQuery<string>("Sp_OrderList", Cntrcountr);
return Request.CreateResponse(HttpStatusCode.OK, country);
}
I'm getting an error
500 Internal server error
Please help me - what's my mistake?

Since your stored procedure doesn't actually return any data you should use the ExecuteSqlCommand method. Try this:
db.Database.ExecuteSqlCommand(
"EXEC Sp_OrderList #OrderId, #OrderName, #OrderData",
new SqlParameter("#OrderId", cnt.OrderId),
new SqlParameter("#OrderName", cnt.OrderName),
new SqlParameter("#OrderData", cnt.OrderData));

Database.SqlQuery takes the sql and then parameters as an array. You are passing in a complex objects and expecting the properties to be translated into parameters. See Database.SqlQuery documentation.
public HttpResponseMessage SaveCountry(OrderList cnt)
{
var country = db.Database.SqlQuery<string>("exec Sp_OrderList #OrderId, #OrderName, #OrderData", cnt.OrderId, cnt.OrderName, cnt.OrderDate);
return Request.CreateResponse(HttpStatusCode.OK, country);
}
That said the reason for the 500 status is because your server code has experienced an unhandled Exception. You should add logging OR learn how to debug your server side code so you can inspect the Exception when it occurs.

Related

DynamicParam AddDynamicParameters not passing data to stored procedure with Dapper (parameter not supplied error)

I've got the following stored procedure in SQL Server
CREATE PROCEDURE [testingDynamic]
#stringa VARCHAR(50),
#datea DATETIME
AS
BEGIN
SELECT #stringa + #datea
END
And this is where it's used in C#
public async Task<string> testingDynamic(string? stringa, Nullable<DateTime> datea)
{
var param = new DynamicParameters(stringa);
param.AddDynamicParams(datea);
string res = await db.ExecuteScalarAsync<string>("testingDynamic", param, commandType: CommandType.StoredProcedure).ConfigureAwait(false);
return res;
}
When calling the method testingDynamic, both parameters have the value of null (I need to check something this way)
When I run it, I get an error
Procedure or function 'testingDynamic' expects parameter '#stringa', which was not supplied
Funny thing, if I populate param using
param.Add("#stringa", stringa);
or even:
.AddDynamicParameters(new { stringa = stringa, datea = datea });
it works just fine.
But if I could use new { ... } I wouldn't need DynamicParameters
Any idea what's causing the problem?
EDIT: now I know that ADO.NET sends string to database as NVARCHAR when using AddWithValue() and my stored procedure parameter is VARCHAR, but I'm using Dapper with AddDynamicParameters().
Does Dapper have the same issue?

Entity Framework Core using stored procedure to delete entity with bool return

I have an entity, lets just call it "Entity", that I want to delete with a stored procedure. The "Entity" entity is relatively complex with a lot of related entities - Hence why, I want to use a stored procedure to delete the Entity.
CREATE PROCEDURE dbo.spDeleteEntity
#EntityId int,
#ServiceResult bit output
AS
BEGIN
.... Delete logic here ...
IF ##ERROR = 0
SET #ServiceResult = 1
ELSE SET #ServiceResult = 0
END
As you can see, the stored procedure takes in an EntityId for the entity, performs my delete logic, and returns a bit - Which in this case is my ServiceResult. Here the ServiceResult is "True"/1 if no errors occur while executing the query, and "False"/0 if errors occur. The problem is now, that I want to be able to execute this stored procedure from .NET Core. My Initial idea was to do something like this
public bool DeleteEntity(Entity Entity)
{
return _context.Entity.FromSqlRaw<bool>("spDeleteEntity {0}", Entity.Id);
}
I believe this doesn't work, because Entity Framework Core does not know what datatype it should expect. From what I can read, Entity Framework Core only accepts types of TEntity. So my question really is, how do I call a stored procedure with Entity Framework Core, so that I can pass an Id and get a bool value returned.
While in your case, you could simply RAISERROR in your procedure to indicate failure.;
try{
_context.Database.ExecuteSqlInterpolatedAsync($"spDeleteEntity {Entity.Id}");
return true;
}catch(...){
return false;
}
There is a way to pass sql parameters in / out of raw sql commands using EF Core with something like;
var entityId = new SqlParameter("#entityId", Entity.Id);
var result = new SqlParameter("#result", SqlDbType.Bit)
{ Direction = ParameterDirection.Output };
_context.Database.ExecuteSqlRaw("EXEC #result = spDeleteEntity #entityId", entityId, result);
return (bool)result.Value;
Call your stored procedure in the try catch and add your SqlParameter that you want to pass to sp like this :
try
{
using(var context = new SampleContext())
{
//Declare storedprocedure parameter
var Idp = new SqlParameter("#IdParam", "Idp");
//Call stored procedure(For async call use ExecuteSqlCommandAsync method)
context.Database.ExecuteSqlCommand("EXEC spName #IdParam", Idp);
}
Return true:
}
catch
{
Return false;
}
In this way if execution of sp occurred with error, it goes to catch and return false and if not it's return true.
Note: if you declare raiseerror in your storedprocedure, you can generates an error message and send it to your application try catch.
More details about raiseerror :
https://learn.microsoft.com/en-us/sql/t-sql/language-elements/raiserror-transact-sql?view=sql-server-ver15

Dapper multi-parameter stored procedure query returns nothing back from database

I have been using Dapper as my ORM for my .NET Core Web Api.
When using Dapper to query a stored procedure from my database with one parameter, it works exactly as expected. When I add more than one parameter, it does not return anything back to my datamodel like it should.
I suspect this has to do either with my syntax or the way I am structuring the query. The stored procedure I am using below works as expected when executed inside a SSMS query window.
Here is my method containing the Dapper Query in my DAL:
public List<Players> C_GetAllActivePlayersInSport(int orgID, int sportID)
{
using (IDbConnection db = new SqlConnection(_connectionString))
{
var returnedData = db.Query<Players>("dbo.spPlayers_GetAllActivePlayers_by_Sport #orgID, #sportID", new { orgID = orgID, sportID = sportID }).ToList();
return returnedData;
}
}
The values passed in make it to the method and query above, but after the query executes, it returns a list with a count of 0.
Any help would be greatly appreciated!
Try:
var returnedData = db.Query<Players>(
"dbo.spPlayers_GetAllActivePlayers_by_Sport",
new { orgID, sportID }, commandType: CommandType.StoredProcedure).ToList();
(note: .AsList() would be marginally preferable)

error from linq while execting stored procedure from linq

I need to execute SQL Server stored procedure from linq-to-sql. I added my stored procedure in data context and used the context in my class. Here is my code to call sql server stored procedure from c# class:
using (DBTestDataContext db = new DBTestDataContext())
{
db.myStoreProcedure(name, address, hasValue);
}
Here, hasValue is of bit type, name and address are of string type and i have pass value in hasValue as true/false making it a bool type. My issue is as the procedure is executed, I am getting the error
Could not translate expression 'value (DBTestDataContext.myStoreProcedure("abc","xyz",true)) into SQL and could not treat it as a local expression.
However, it executed successfully in sql server:
EXEC dbo.myStoreProcedure #name="abc", #address = "xyz", #hasValue = true
it is working fine. Is this the issue associated with db.myStoreProcedure ??? For any data entered, this code is not working. How can it be fixed
Can anyone help me how to fix this. thanks in advance..
Try executing it like this .
var param1 = new SqlParameter("#param1", 1);
var param2 = new SqlParameter("#param2", 2);
var results = context.Database.SqlQuery<StronglyTypedObject>
("SPName #param1, #param2",param1, param2).ToList()

How can I run a stored procedure that has no return values from C# with my db context?

I am using the following code to run a stored procedure:
MyContext db = new MyContext();
var a = db.Database.SqlQuery<string>("dbo.getQuestionUIdsByTopicId #TopicId",
new SqlParameter { ParameterName = "TopicId", Value = testTopicId });
This works good but now I will have a stored procedure that does not return any data other than a return code.
How can I execute a stored procedure with a parameter using my context db.Database and have the stored procedure return only a return code? If someone could give an example of a 3-4 line SP and how it returns a return code that would also be a great help.
You can use ExecuteSqlCommand to send non-query commands to the database.
int result = db.Database.ExecuteSqlCommand("exec sproc...");
See this link for more info.

Categories

Resources