Working with stored procedure in LINQ? - stored-procedures

In web application, I am using LINQ to call a procedure, the procedure is parameter procedure. but when I am passing arguments it is giving errors, This is my code:
MyLinqsDataContext DataContext=new MyLinqsDataContext ();
int eno=Convert.ToInt32 (txtempno.Text );
int dep=Convert .ToInt32 (txtDep.Text );
var sqr = from qr in DataContext.USP_Insert_Emp(eno, txtName.Text, dep)
select qr;
But is giving error like:
Could not find an implementation of the query pattern for source type int. Select not found.
This is my Proc :
create procedure USP_Insert_Emp(#empid int,#ename varchar(60),#deptid int)
as
begin
insert into Emp (empid ,ename,deptid ) values (#empid ,#ename ,#deptid)
end

DataContext.USP_Insert_Emp returns an int.
The error you are getting is because you are trying to call Select on an int and not an IEnumerable<T>.

Related

Procedure or Function expects parameter which was not supplied even though it is supplied

Hello i cannot wrap my head around why i get the error saying that this SP expects #id which was not given when it is quite clearly given. this is how the code looks
public Task<bool> InsertMessage(Message msg)
{
return CallDatabase(async (connection) =>
{
var affectedows = await connection.ExecuteAsync(
"messages_insert",
new
{
msg.Id,
msg.Group,
msg.GroupUserId,
msg.userId,
msg.StartTime,
msg.FinishTime
},
commandTimeout: 3600,
commandType: CommandType.StoredProcedure
);
return affectedows == 1;
});
}
And here is the SP in the db
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[messages_insert]') AND type in (N'P', N'PC'))
BEGIN
PRINT 'DROP PROCEDURE [dbo].[messages_insert]';
DROP PROCEDURE [dbo].[messages_insert];
END
GO
PRINT 'CREATE PROCEDURE [dbo].[messages_insert]';
GO
CREATE PROCEDURE [dbo].[messages_insert]
#id BIGINT, -
#group INT,
#group_user_id VARCHAR(100),
#user_id VARCHAR(100),
#start_time DATETIME,
#finish_time DATETIME
AS
BEGIN
INSERT INTO messages(id, group, group_user_id, user_id, start_time, finish_time)
VALUES(#id, #group, #group_user_id, #user_id, #start_time, #finish_time);
END
GO
I really cant see were i am going wrong and the stack trace really says nothing
Exception: System.Data.SqlClient.SqlException (0x80131904): Procedure or function 'messages_insert' expects parameter '#id', which was not supplied.
Ensure that msg.Id is not null when calling the stored procedure.

delphi Invalid enum value '_24170'

I have my dll, it contains function:
function GetPdfReport(
//this is string representation of MyEnum
AStringParam : Pchar
): TByteDynArray; stdcall; export;
var
//my vars
begin
try
try
//i try to pass incorrect string value on purpose to get exception
MyEnumVariable := TRttiEnumerationType.GetValue<MyEnum>(AStringParam);
//code hide
except
on E : Exception do
begin
//log error
Log.Error(E.ClassName + ' : ' + E.Message, 'errors');
end;
end;
finally
//dispose
end;
Then i get exception:
The InnerException message was 'Invalid enum value '_24170' cannot be
deserialized into type
'MyEnum'.
I want log exception message with string value that i passed as parameter but not some unclear numbers like '_24170'. How can I do this?
Update:
Let's say i have MyEnum with 3 values (One, Two, Three), and when i pass to my function string "Five" i want to see exception like this:
Invalid enum value 'Five' cannot be deserialized into type 'MyEnum'.
Thanks.
The code that you present does not raise an exception in case the supplied text does not match one of the enum values. Instead a value of -1 is returned. Of course, -1 is not a valid enum value so that makes TRttiEnumerationType.GetValue a rather questionable method if you wish to perform error handling.
You would need to test for this yourself. Rather than using TRttiEnumerationType it might be simpler to go directly to GetEnumValue, which returns an integer and so makes error checking a little simpler to write.
var
OrdinalValue: Integer;
Value: MyEnum;
....
OrdinalValue := GetEnumValue(TypeInfo(MyEnum), AStringParam);
if OrdinalValue = -1 then
// handle error
Value := MyEnum(OrdinalValue);
Naturally you'd want to wrap this in a method to make it re-usable.

call a stored procedure with more than one result sets into another procedure and work with them

I have a stored procedure that have 2 result sets and I want to call this sp into another stored procedure and get both it’s result sets and work with them. I have searched in Internet and Knew about the new fearture in sql server 2012 for this purpose. It is ‘RESULT SETS’.
Except using ‘Result sets’, is there another solution for call storedprocedure with more than one resultset into another procedure and work with them?
Pinal Dave has an example for using ‘Result Sets’
USE AdventureWorks2008R2
GO
CREATE PROCEDURE mySP1 (#ShiftID INT, #JobCandidateID INT)
AS
-- ResultSet 1
SELECT [ShiftID],[Name],[StartTime],[EndTime],[ModifiedDate]
FROM [HumanResources].[Shift]
WHERE [ShiftID] = #ShiftID
-- ResultSet 2
SELECT [JobCandidateID],[BusinessEntityID],[ModifiedDate]
FROM [HumanResources].[JobCandidate]
WHERE JobCandidateID = #JobCandidateID
CREATE PROCEDURE mySP2
AS
EXEC mySP1 #ShiftID = 2, #JobCandidateID = 5
WITH RESULT SETS
( ( [ShiftID] TINYINT,[Name] NVARCHAR(50),[StartTime] DATETIME, [EndTime] DATETIME,[UpdateDate] DATETIME -- Notice Name Change
),([JobCandidateID] INT,[BusinessEntityID] INT,[ModifiedDate] DATETIME ));
When we use the Result Set, we have the mysp1 results into these:
For ResultSet1:
[ShiftID] TINYINT,[Name] NVARCHAR(50),[StartTime] DATETIME,
[EndTime] DATETIME,[UpdateDate] DATETIME
And for Resultset2:
[JobCandidateID] INT,[BusinessEntityID] INT,[ModifiedDate] DATETIME
But now I want to query on these results in mySp2. How can I do this.
How can I select the values from :
[ShiftID] TINYINT,[Name] NVARCHAR(50),[StartTime] DATETIME
,[EndTime] DATETIME,[UpdateDate] DATETIME
And
[JobCandidateID] INT,[BusinessEntityID] INT,[ModifiedDate] DATETIME
The best solution may be using output variables in mySP1
CREATE PROCEDURE mySP1 (
#ShiftID INT
, #JobCandidateID INT
, #CUR1 CURSOR VARYING OUTPUT
)
SET NOCOUNT ON;
SET #CUR1 = CURSOR
FORWARD_ONLY STATIC FOR
SELECT [ShiftID],[Name],[StartTime],[EndTime],[ModifiedDate]
FROM [HumanResources].[Shift]
WHERE [ShiftID] = #ShiftID
OPEN #CUR1;
GO
to calling this sp:
DECLARE #MyCursor CURSOR;
EXEC dbo.mySP1 #ShiftID = 1, #JobCandidateID = 1, #CUR1 = #MyCursor OUTPUT;
WHILE (##FETCH_STATUS = 0)
BEGIN;
FETCH NEXT FROM #MyCursor;
END;
CLOSE #MyCursor;
DEALLOCATE #MyCursor;
Use a combination of this with a standar output or just declare another cursor output.

Return a result set as output param in a sybase stored proc

I have a stored procedure, in which I want to simply store result of a select statement in an output parameter and return that , how can i do that.
I would appreciate if you give me the right syntax of it, since i am new to DB and Sybase specially, that's why i am just giving u a pseudo code for that..
/pseudo code
create my_proc(in_param i,out_param o1,out_param o2){
.....other select and insert statements
.....
if(xyz=true){
o1 = select * from emplyees
}
return o1,o2
}
You don't need output parameters to return result of query, try below code
create procedure proc1
(
#val1 integer
)
as
begin
select * from emplyees
end
/pseudo code
create my_proc(in_param int,out_param1 int out,out_param2 int out)
BEGIN
.....other select and insert statements
if(xyz=true)BEGIN
select out_param1=e.col1,out_param1=2=e.col2 from emplyees e
END
END
Modify datatypes accordingly
Thanks,
Gopal

I cannot get the output parameter when use function import by Entity Framework

Here's my SQL Server stored procedure :
ALTER PROCEDURE [dbo].[SearchUser]
(#Text NVARCHAR(100),
#TotalRows INT = 0 OUTPUT)
AS
BEGIN
SELECT #TotalRows=1000
SELECT * from Users
END
And my C# code
using (var context = new TestDBEntities())
{
var outputParameter = new ObjectParameter("TotalRows", typeof(Int32));
context.SearchUser("", outputParameter);
Response.Write(outputParameter.Value);
}
However outputParameter.Value always is null.
Could anybody tell me why?
Output parameters filled by its actual values during the execution of the stored procedure.
But table-valued stored procedure actually get executed only in moment when you're trying to iterate resulting recordset, but not calling a wrapper method.
So, this DOES'T work:
using (var context = new TestDBEntities())
{
var outputParameter = new ObjectParameter("TotalRows", typeof(Int32));
context.SearchUser("", outputParameter);
// Paremeter value is null, because the stored procedure haven't been executed
Response.Write(outputParameter.Value);
}
This DOES:
using (var context = new TestDBEntities())
{
var outputParameter = new ObjectParameter("TotalRows", typeof(Int32));
// Procedure does not executes here, we just receive a reference to the output parameter
var results = context.SearchUser("", outputParameter);
// Forcing procedure execution
results.ToList();
// Parameter has it's actual value
Response.Write(outputParameter.Value);
}
When you're working with stored procedures what don't return any recordset, they execute immediately after a method call, so you have actual value in output parameter.
We had a simular issue due to defered excecution our unit tests failed. In short if you have a stored proc that does NOT return anything you need to be sure to set the response type as 'None' when set as 'None' it will be excecuted when called and not defered.
In case you return anything (E.g. Scalar type of String results) it will excecute it when you use the result even if that .Count() or .ToList() is outside of the method that contains the function call.
So try not to force excecution if not need, when needed it should excecute but be sure to declare it correctly or it might not work.
I have same problem before. The main reason I think that the entities framework has the bug in case the user stored procedure has output parameter and return a result set. For example:
ALTER PROCEDURE [dbo].[SearchTest]
(
#RowTotal INT = 0 OUTPUT,
#RowCount INT = 0 OUTPUT
)
AS
BEGIN
SET NOCOUNT ON
SELECT * FROM SomeThing
SELECT #RowTotal = 1233, #RowCount = 5343
END
However if you change the user stored procedure as following, you can get the output params
ALTER PROCEDURE [dbo].[SearchTest]
(
#RowTotal INT = 0 OUTPUT,
#RowCount INT = 0 OUTPUT
)
AS
BEGIN
SET NOCOUNT ON
SELECT #RowTotal = 1233, #RowCount = 5343
END
You can workaround as following:
ALTER PROCEDURE [dbo].[SearchTest]
AS
BEGIN
DECLARE #RowTotal INT, #RowCount INT
SET NOCOUNT ON
SELECT #RowTotal = 1233, #RowCount = 5343
SELECT #RowTotal AS RowTotal, #RowCount AS RowCount, s.*
FROM SomeThing s
END
If anybody has better solution, please tell me

Resources