Error in Function EF - c#

i use Entity Framework + SQl 2008 + .Net Framework 4 + SP in SQL.
and crate Function in EF for Insert value into sql.
fro EX:
Function Import Name: InsertStudent
stroed Procedure Name: InsertStudent
Returns a Collection Of: Scalars: Int32
SP:
create proc InsertStudent
(
#DateReg datetime,
#stdLastName nvarchar(50),
#stdFirstName nvarchar(50),
#Description nvarchar(500)
)
INSERT INTO Student(DateReg,stdLastName,stdFirstName,[Description])
VALUES (#DateReg,#stdLastName,#stdFirstName,#Description)
the Date Saving at SQL but Error in Function EF:
The data reader returned by the store data provider does not have enough columns for the query requested.

i think you need to insert primary key value for through sp.
create proc InsertStudent
(
#stdID int,
#DateReg datetime,
#stdLastName nvarchar(50),
#stdFirstName nvarchar(50),
#Description nvarchar(500)
)
INSERT INTO Student(stdID,DateReg,stdLastName,stdFirstName,[Description])
VALUES (#stdID,#DateReg,#stdLastName,#stdFirstName,#Description)

Related

SELECT statement won't return row first time after INSERT commit transaction

I have two stored procedures, one AddReportsApi for inserting data with a BEGIN TRANSACTION and COMMIT TRANSACTION, and the other GetReportsApi for selecting the data for inserted row.
I call the INSERT stored procedure first, then I call the SELECT stored procedure but sometimes it does not return any rows for the passed in SearchItemId which is used in the WHERE predicate.
If I execute the SELECT stored procedure a second time, it returns the expected rows.
Is there a delay in inserting the data to the table? Please note that the stored procedures are called from HangFire background job framework. From my test, HangFire should not affect the INSERT and SELECT stored procedure calls. The INSERT stored procedure is called multiple times within a minute to insert the records into the ReprotsApi table.
Insert stored procedure:
CREATE PROCEDURE [dbo].[AddReportsApi]
#OrderID nvarchar(50),
#SearchItemId nvarchar(50),
#SubjectID nvarchar(50),
#SearchType nvarchar(50),
#ApiName nvarchar(50),
#ApiRequest text,
#ApiResponse text,
#IsActive bit,
#CreatedOn datetime,
#CreatedBy nvarchar(50),
#ModifyOn datetime,
#ModifyBy nvarchar(50),
#HitType nvarchar(2)
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRANSACTION
INSERT INTO [dbo].[ReportsApi] ([OrderID], [SearchItemId], [SubjectID], [SearchType],
[ApiName], [ApiRequest], [ApiResponse], [IsActive],
[CreatedOn], [CreatedBy],
[ModifyOn], [ModifyBy], [HitType])
VALUES (#OrderID, #SearchItemId, #SubjectID, #SearchType,
#ApiName, #ApiRequest, #ApiResponse, #IsActive,
#CreatedOn, #CreatedBy,
#ModifyOn, #ModifyBy, #HitType)
IF (##ERROR != 0)
BEGIN
ROLLBACK TRANSACTION
END
ELSE
COMMIT TRANSACTION
END
SELECT stored procedure:
CREATE PROCEDURE [dbo].[GetReportsApi]
#OrderID nvarchar(50)
,#SearchItemId nvarchar(50)
,#SubjectID nvarchar(50)
,#CreatedBy nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
SELECT [Id]
,[OrderID]
,[SearchItemId]
,[SubjectID]
,[SearchType]
,[ApiName]
,[ApiRequest]
,[ApiResponse]
,[IsActive]
,[CreatedOn]
,[CreatedBy]
,[ModifyOn]
,[ModifyBy]
,[HitType]
FROM [dbo].[ReportsApi] WHERE [SearchItemId] = #SearchItemId
END
it might be because indexes are being rebuilt under the hood after the insert completes.
This can give dirty/phantom reads.
If you have an index on [SearchItemId] then the 2nd query might use this but the index may still being refreshed.
This can even affect clustered indexes if you are inserting into the middle of the B-Tree.
It might be worth sticking a sleep(10000) or WAITFOR DELAY '00:00:10'; into your code...
(That's 10 sec but you could experiment with different timings.)
Good luck!

How can I call a stored procedure with INSERT using LINQ?

Is there any possible way to execute a non query without having to assign it to a LINQ to SQL class?
Let's say I have this procedure and I want to INSERT only if the Town_Name (UNIQUE CONSTRAINT) is non existent. Otherwise, the UPDATE is executed. This procedure works well and does the job when executed through SQL Server. However, I can't manage to execute it through C# code.
I am trying to avoid using SQL client, as part of my coursework, my little application has to be capable of selecting, inserting / updating and deleting data using LINQ.
The approach I'm taking always results in 0 rows affected.
// Call Procedure.
db.P_SaveClient("000000001M", "Test", "Dummy", null, "+35699999999");
-- Procedure to be executed.
CREATE PROCEDURE Appointment.SaveClient
(
#id NVARCHAR(10),
#firstName NVARCHAR(35),
#lastName NVARCHAR(35),
#tel NVARCHAR(12),
#mob NVARCHAR(12)
)
AS
BEGIN
DECLARE #clientCount TINYINT
SELECT #clientCount = COUNT(Client_ID)
FROM Appointment.Client
WHERE Client_ID = #id
IF #clientCount = 0
BEGIN
INSERT INTO Appointment.Client
VALUES (
#id
, #firstName
, #lastName
, #tel
, #mob
)
END
ELSE
BEGIN
UPDATE Appointment.Client
SET Client_ID = #id
, First_Name = #firstName
, Last_Name = #lastName
, Telephone = #tel
, Mobile = #mob
END
END
Some tutorials I found:
https://www.youtube.com/watch?v=dlXT-vE46sc
https://www.youtube.com/watch?v=-PAMtSwplu8
You're looking for a Merge statement to execute in SQL, which you could call via the stored proc. This will allow you to insert or update depending on whether it was found. It can even return the ID of the record inserted which can save you another query.
Merge Town t
using ( select #Town_Name as 'Town_Name')
src on (src.Town_Name = t.Town_Name )
when NOT MATCHED then
insert (Town_Name) values (src.Town_Name)
output INSERTED.Town_ID
See here for syntax and more examples:
https://msdn.microsoft.com/en-us/library/bb510625.aspx

Insert list of values into a SQL Server table with stored procedure

How can I pass a list of column data into a stored procedure?
My stored procedure is
ALTER PROCEDURE [dbo].[Register]
#Id int,
#Name nvarchar(50)
AS
BEGIN
BEGIN TRY
INSERT INTO dbo.Group (Id, Name)
VALUES(#Id, #Name)
SELECT 0
END TRY
BEGIN CATCH
SELECT -1
END CATCH
END
GO
I want pass like this data for insert into this table
#Id = 1,2,3,4,5
#Name = 'test1,test2,test3,test4,test5'
and result like this
Id Name
1 test1
2 test2
3 test3
4 test4
5 test5
A "list" or "array" in SQL Server is ..... a table. So if you're on SQL Server 2008 or newer (you didn't specify), then use the table-valued parameter feature of SQL Server to pass a table of value to your stored procedure
-- Create a table type to match your input parameters
CREATE TYPE IdNameTable AS TABLE
( ID INT, Name NVARCHAR(50) );
GO
-- change your stored procedure to accept such a table type parameter
ALTER PROCEDURE [dbo].[Register]
#Values IdNameTable READONLY
AS
BEGIN
BEGIN TRY
INSERT INTO dbo.Group (Id, Name)
-- get the values from the table type parameter
SELECT
Id, Name
FROM
#Values
SELECT 0
END TRY
BEGIN CATCH
SELECT -1
END CATCH
END
GO
See the extensive and freely available SQL Server Books Online documentation for more details on the table-valued parameter feature and how to use it
If you want to use this from T-SQL, use this code:
-- declare a variable of that table type
DECLARE #InputTable IdNameTable
-- insert values into that table variable
INSERT INTO #InputTable(ID, Name)
VALUES (1, 'Test 1'), (2, 'Test 2')
-- execute your stored procedure with this table as input parameter
EXECUTE [dbo].[Register] #InputTable
If you want to use this from C# or VB.NET, see Michael Edenfield's link in comments.

Convert user-defined function to stored procedure for EF

This is my user-defined function used in a project:
CREATE FUNCTION [dbo].[Encrypt]
(
#Password nvarchar(4000)
)
RETURNS varbinary(4000)
AS
BEGIN
SELECT #Password = CONVERT(nvarchar(4000),#Password);
RETURN HashBytes('SHA1', #Password);
END
GO
I need Entity Framework so, it's possible find a way to convert this one in a stored procedure in SQL Server 2012 Express?
Procedure Definition
CREATE PROCEDURE [dbo].[usp_Encrypt]
#Password nvarchar(4000),
#HashedPass varbinary(4000) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SET #HashedPass = HashBytes('SHA1',CONVERT(nvarchar(4000),#Password));
END
EXECUTE PROCEDURE
DECLARE #RtnHashedPass varbinary(4000);
EXECUTE [dbo].[usp_Encrypt]
#Password = 'myPassword'
#HashedPass = #RtnHashedPass OUTPUT
SELECT #RtnHashedPass --<-- Do what ever you want to do with this value

Stored procedure with JSON input to create a table definition

I am to create a stored procedure to create a table to capture form data, this is part of a bigger project to create a Form Generator.
I was wondering if anyone had created a stored procedure that took a stringified JSON object as input and created the the table based on this schema?
I'm still toying with this in my brain as to whether I should be doing this within the sproc (preferable) or writing dynamic sql within a C# Service.
Personally I wouldn't approach this problem by passing the JSON string to a stored procedure. However, if you wish to do it this way you could pass the JSON object directly to the stored procedure and then manipulate the string as below. I have provided the code to manipulate the table name and create a table based upon the example JSON string '{TABLENAME:TABLENAME, Fields: {field1:varchar, field2: int }}'. You would then have to modify this to include fields and datatypes based upon the string.
CREATE PROCEDURE CreateTableFromJSON
(
#JSON VARCHAR(100)
)
AS
DECLARE #TableName VARCHAR(100)
SET #TableName = SUBSTRING(#json, CHARINDEX(':', #json)+1, CHARINDEX(',', #json) -CHARINDEX(':', #json)-1)
DECLARE #SQL VARCHAR(100)
SET #SQL = 'CREATE TABLE ' + #TableName + ' (ID INT)'
EXEC(#SQL)
GO
EXEC CreateTableFromJSON '{TABLENAME:TABLENAME, Fields: {field1:varchar, field2: int }}'

Categories