Getting an simple value with Entity Framework Stored Procedure - c#

I have a Stored Procedure and turns me an integer. I want to take and use that integer but get an error like:
'System.Data.Objects.ObjectResult1[System.Nullable1[System.Int32]]'
type object couldn't assign to 'System.IConvertible'.
Here is my Stored Procedure:
CREATE PROC prDetectMurderer(#carId INT)
AS BEGIN
SET NOCOUNT ON
SELECT TOP 1 DriverId FROM EventTable
WHERE CarId = #carId
AND Damage = 'false'
ORDER BY EventId DESC
SET NOCOUNT OFF
END
And my c# code:
int sofor = Convert.ToInt16(entity.prDetectMurderer(11));
How can I solve it ?

This answer https://stackoverflow.com/a/35832669/3572241 shows how to get an int from a stored procedure, using EF.

Related

User defined type from stored procedure not detected in LINQ

I have created this stored procedure:
CREATE PROCEDURE [dbo].[zsp_MoveItemsToFolder]
(#IdListToMove IdListToMove READONLY,
#FolderId INT,
#UserId INT)
AS
BEGIN
DECLARE #Rowcount INT = 1;
WHILE (#Rowcount > 0)
UPDATE TOP (5000) dbo.SingleScannedItems --<-- define Batch Size in TOP Clause
SET MyListId = #FolderId
WHERE SingleScannedItemId IN (SELECT l.SingleScannedItemIds
FROM #IdListToMove l)
AND UserId = #UserId
SET #Rowcount = ##ROWCOUNT;
CHECKPOINT; --<-- to commit the changes with each batch
END
Prior to that I have created a user defined type in SQL like this:
CREATE TYPE [dbo].[IdListToMove] AS TABLE(
[SingleScannedItemIds] int NULL
);
And once I have imported the procedure into the C# LINQ the only parameters that I can see are FolderId and UserId.
However the #IdListToMove user defined type is not visible in the imported stored procedure :/...
So my question is: why is the user defined type not visible in the imported stored procedure (that is imported through the Entity Framework 6)
How do I fix this so that I can pass the list through C# into the stored procedure?
Can someone help me out?
Edit: here's the modified procedure with #Marc Gravel's suggestions:
ALTER PROCEDURE [dbo].[zsp_MoveItemsToFolder]
(#IdListToMove NVARCHAR(MAX),
#FolderId INT,
#UserId INT)
AS
BEGIN
DECLARE #Rowcount INT = 1;
WHILE (#Rowcount > 0)
UPDATE TOP (5000) dbo.SingleScannedItems --<-- define Batch Size in TOP Clause
SET MyListId = #FolderId
WHERE (EXISTS (SELECT 1
FROM dbo.SplitStringProduction(#IdListToMove,',') S1
WHERE SingleScannedItemId = S1.val))
AND UserId = #UserId
AND MyListId <> #FolderId
SET #Rowcount = ##ROWCOUNT;
CHECKPOINT; --<-- to commit the changes with each batch
END

EF core stored procedure : getting 'No best type found for implicitly-typed array' error while posting multiple parameters

I try using stored procedures with EF core. My purpose is that getting rows count from database table, but I can't send multiple parameters. I am getting an error:
No best type found for implicitly-typed array
Actually I don't know how to use Linq syntax. Thanks in advance
Stored procedure:
create proc sp_getExistorNExistCountStd
#Date datetime2(7),
#ClassId int,
#Absent bit,
#Count int out
as
begin
select #Count = COUNT(*)
from RollCalls
where DateRollCall = #Date
and ClassId = #ClassId
and [Absent] = #Absent
return #Count
end
C#
int ExistStdCount = db.RollCalls.FromSql("sp_getExistorNExistCountStd #p0 ,#p1, #p2",
// getting error in this section
parameters: new[] {DateTime.Now.Date, classIds[i], true }).FirstOrDefault();
I didn't find the solution to count rows using output parameter but I reached another solution.. This method gave me what I wanted
Create proc [dbo].[sp_getExistorNExistCountStd]
#Date datetime2(7),
#ClassId int,
#Absent bit
as
begin
select Id from RollCalls
where DateRollCall=#Date
and ClassId=#ClassId
and [Absent]=#Absent
end
int ExistStdCount = db.RollCalls.FromSql("sp_getExistorNExistCountStd #p0 ,#p1, #p2",
DateTime.Now.Date.ToString("yyyyMMdd"), classIds[i], 0).ToList().Count();
Why do You use stored procedure?
The EF generates sql really smart. Did You tried: db.RollCalls.Where(rc => DateTime.Now.Date.Equals(rc.DateRollCall)/* && other conditions */).Count()

ExecuteStoreCommand can't return string with SqlParameter output

Something really weird today.
When I try to call a stored procedure in SQL Server with the objectContext from Entity Framework, using the function ExecuteStoreCommand, it always tries to convert to 'string' value to 'int' .. I don't know why.
Even if I set the output as an NvarChar type.
My exception is
Failed converting the varchar value 'text' to int data type
Here is my C# code:
public virtual string GetCardCodeLinkedToAttestation(string atBuisnessCode)
{
// Input param - String
SqlParameter atBuisnessCodeParameter = new SqlParameter("atBuisnessCode", atBuisnessCode);
// The output param - String
SqlParameter retval = new SqlParameter("retval", SqlDbType.NVarChar,15);
retval.Direction = ParameterDirection.Output;
((IObjectContextAdapter)this).ObjectContext.ExecuteStoreCommand("exec #retval = sp_GetCardCodeLinkedToAttestation #atBuisnessCode", atBuisnessCodeParameter, retval);
return (string)retval.Value;
}
Here is my stored procedure in SQL Server (I explicitly return 'test' for be sure is a string ):
ALTER PROCEDURE [dbo].[sp_GetCardCodeLinkedToAttestation]
#atBuisnessCode nvarchar(9)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #retval varchar(15);
set #retval= '';
-- Insert statements for procedure here
SET #retval = (SELECT TOP 1 [CardCode]
FROM [SC-SAP01].[SWC_PROD].[dbo].[OCPR]
WHERE [U_Attestation] = #atBuisnessCode)
RETURN 'test';
END
GO
Exception :
Failed converting the varchar value 'text' to int data type
I tried to set the value without return it, and declare the output in my stored procedure, but the value returned is always NULL.
Here you need to use Output as return will always return int datatype.
By default, the successful execution of a stored procedure will return 0
Please try below code:
#atBuisnessCode nvarchar(9),
#retval varchar(15) OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #retval varchar(15);
set #retval= '';
-- Insert statements for procedure here
set #retval= (SELECT TOP 1 [CardCode] FROM [SC-SAP01].[SWC_PROD].[dbo].[OCPR] WHERE [U_Attestation] = #atBuisnessCode)
--return 'test';
END
GO
I find, Finally i use (ExecuteStoreQuery) instead of (ExecuteStoreCommand). Where i put my sql directly Inside. And it's return me the string result of my select. Easy . Thank you for try to help me ;-) .
public virtual string GetCardCodeLinkedToAttestation(string atBuisnessCode)
{
string return_value = ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<string>
(string.Format("SELECT TOP 1 [CardCode] FROM [SC-SAP01].[SWC_PROD].[dbo].[OCPR] WHERE [U_Attestation] = '{0}'", atBuisnessCode)).FirstOrDefault();
return string.IsNullOrWhiteSpace(return_value) ? string.Empty : return_value;
}

Passing value from int as output parameter to a int Variable using LINQ in c#

I have a stored Procedure as
ALTER PROCEDURE [dbo].[customers_iu] (#intId as int, #strName as nvarchar(100), #strSname as nvarchar(100),#intInsupdt as int = 0, #intGnrtdid as int OUTPUT)
AS
BEGIN
SET NOCOUNT ON;
if #intInsupdt = 1
begin
insert into dbo.customers (cust_Name, cust_Sname, cust_Tinno) values (#strName, #strSname,#strTinno)
set #intGnrtdid = (select ident_Current('dbo.customers'))
end
else if #intInsupdt = 0
begin
update dbo.customers set cust_Name = #strName, cust_Tinno = #strTinno where cust_Id = #intId ;
set #intGnrtdid = #intId
end
END
I want to get #intGnrtdid value to a int Variable in using LINQ.
See Scott Guthrie's excellent blog series on Linq to SQL. Part 6 covers calling stored procedures. An out parameter would simply be represented by a ref parameter when calling your strongly typed stored procedure from code.

Get value output from SQL Server stored procedure into variable

This seems to be a simple question but nevertheless I haven't found an answer yet.
I have the following stored procedure
CREATE PROCEDURE [dbo].[AllocateId]
AS
BEGIN TRANSACTION
UPDATE TOP(1) IdReservation
SET IsAllocated = 1
OUTPUT DELETED.Id
WHERE IsAllocated = 0
COMMIT TRANSACTION
GO
It's been used in C# + EF code without a problem via ExecuteFunction of ObjectContext
ObjectResult<int> objectResult = ExecuteFunction<int>("AllocateId");
However when I try to call it directly from SQL script it doesn't seem to work
declare #Id int
EXEC #Id = [dbo].[AllocateId]
#Id is always 0. How do I get the value into #Id variable in sql script?
Procedure return value is different from result set(s) returned by that procedure. Your stored procedure returns a result set and does not return a return value (which ends up being null, which gets converted to 0 implicitly upon exiting the procedure).
To get the resultset your existing procedure retuns, you need insert ... exec:
declare #t table (id int);
insert into #t
exec [dbo].[AllocateId];
If you want to return a value as a return value as well, you should amend you stored procedure:
CREATE PROCEDURE [dbo].[AllocateId]
AS
BEGIN TRANSACTION
declare #id int;
UPDATE TOP(1) IdReservation
SET #id = Id, IsAllocated = 1
OUTPUT DELETED.Id
WHERE IsAllocated = 0
COMMIT TRANSACTION
return #id;
Then it will work in the way you describe in the question.

Categories

Resources