Get values from Stored Procedure select query Entity Framework - c#

I have below stored procedure :-
CREATE PROCEDURE [dbo].[DELETE_DATA_BY_TIMESTAMP]
#NUMBER_OF_DAYS_BEFORE int
AS
BEGIN
IF OBJECT_ID('dbo.TableFileID', 'U') IS NOT NULL
DROP TABLE TableFileID;
select FileID into TableFileID from
[dbo].[OUTPUT_JSON_LOG]
where OutJsonStatus in ('Success' , 'Failed')
and convert(date,CreatedOn)<convert(date,getdate()-#NUMBER_OF_DAYS_BEFORE)
DELETE FROM OUTPUT_JSON_LOG
.... Some DML Queries .....
select * from TableFileID
END
I want to get all the list of FileIds from select query in procedure :-
select * from TableFileID
I updated Entity framework edmx file.
in designer I can see function as :-
Public ObjectResult<Nullable<global::system.Int32>> DELETE_DATA_BY_TIMESTAMP(...)
{
....
....
return base.ExecuteFunction<Nullable<global::system.Int32>>("DELETE_DATA_BY_TIMESTAMP",..);
}
When I am calling this function :-
var FileIds=context.DELETE_DATA_BY_TIMESTAMP(...);
return FileIds.ToList();
It always shows count 0 for list.
But internally it processes all fileIds.
How can I get this list of fileIds with above procedure.

Related

How to return a Dictionary<K,V> from a stored procedure with other data

I have a result set of data I want to return from a stored Procedure:
CREATE PROCEDURE Notifications.Email_GetSubstitutions
#ReportType varchar(100)
AS
SELECT et.TemplateID, et.OnlineTemplateID, et.OnlineTemplateID, et.EmailFrom, et.ReportType, els.EmailSubstitutionName, erts.EmailSubstitutionID, erts.EmailSubstitutionResult
FROM Notifications.Email_Template et
INNER JOIN Notifications.Email_Reference_TemplateSubstitution erts ON erts.TemplateId = et.TemplateID
INNER JOIN Notifications.Email_List_Substitution els ON erts.TemplateSubstitutionId = els.EmailSubstitutionID
WHERE et.ReportType = #ReportType
GO
I want the erts.EmailSubstitutionID and erts.EmailSubstitutionResult to be returned as a Dictionary in the (C#) Entity Framework sProc result.
Is there an extension method or something I can do in EF to convert only those two items to a Dictionary or should I do a separate sProc call that returns the results in and convert that?

Retrieve table data from stored procedure using entity framework

I'm using Entity Framework v6. I have a stored procedure as shown below
CREATE PROCEDURE [dbo].[GetCountryList]
(
#CustomerName VARCHAR(MAX),
#SearchCriteria VARCHAR(MAX)
)
AS
BEGIN
SET NOCOUNT ON
SELECT CountryID, CountryName FROM dbo.Table1
WHERE CustomerName = #CustomerName AND CountryName = #SearchCriteria
END
Now I have a model class
public class CountryName
{
public int CountryId { get; set; }
public string CountryName { get; set; }
}
So I want to get the result of the SELECT query in a List<CountryName> type
List<CountryName> countryList = null;
using (DbEntities dbContext = new DbEntities())
{
countryList = //my code to collect the result
}
Well, I could have run a LINQ to SQL directly on the table but unfortunately my requirement in to get the data from stored procedure. So, how can I do it?
You need to Import the stored procedure as a Function. Right-click on the workspace area of your Entity model and choose Add -> Function Import.
In the Add Function Import dialog, enter the name you want your stored procedure to be referred to in your model for example GetCountryListSP, choose your procedure from the drop down list, and choose the return value of the procedure to be Entities and choose CountryName from the drop down list.
Then in the code:
var result = db.GetCountryListSP();//Send parameters too
With this approach you prevent returning -1 of the stored procedure. Please check this post for more details about stored procedure problem with Entity Framework.
You can do it without importing. Something like that:
var countryList = dbContext.Database.SqlQuery<CountryName>("[GetCountryList]").ToList();
EntityFramework sometimes won't recognize or import SPs ))) So, that's why I saving my hours with this snippet.

Entity Framework doesn't support stored procedures which build result sets from Dynamic queries or Temporary tables

I've written the following stored proc, which works fine. What I want to do with it though is use it an entity data model. However using it in the entity data model maps to a return type of integer, and a value of zero.
How do I get the SP to return the actual data instead of an integer using the DataContext ?
IF EXISTS (SELECT * FROM SYS.OBJECTS WHERE TYPE = 'P' AND NAME = 'myProc') DROP PROCEDURE myProc;
GO
CREATE PROCEDURE [dbo].myProc
#START DateTime, #STOP DateTime
AS
BEGIN TRY
CREATE TABLE #Temp (download_Pk int);
INSERT INTO #Temp
SELECT download_pk FROM t1
UNION ALL
SELECT download_pk FROM t2;
WITH
x as
(
SELECT ID as Caps_Pk,
rootID as [Caps_RootId],
Case400Series as [Case],
SUBSTRING(c1, CHARINDEX('_', c1,1)+1, LEN(c1)) as [Customer],
run as Run,
SUBSTRING(c2, 1, CHARINDEX('_', c2, 1) -1) as [Sample],
SUBSTRING(c2, CHARINDEX('_', c2,1)+1, len(c2)) as [Amplification],
projectTitle,
DateAdded as [UploadTime],
UserId as [User]
FROM t3
WHERE DateAdded >= #START AND DateAdded <= #STOP AND
[User] in (SELECT name FROM ViewUsers WHERE Site = 'abc' AND Role = 'def')
)
SELECT *
FROM x
WHERE Caps_Pk NOT IN (Select download_Pk from #Temp)
DROP TABLE #Temp;
END TRY
BEGIN CATCH
DROP TABLE #Temp;
END CATCH
GO
Thanks in Advance.
Have you looked at this Code First Stored Procudure, this works great for me, it also has a NuGet Pckage that you can install.
found the answer here: EF4 - The selected stored procedure returns no columns
"EF doesn't support importing stored procedures which build result set from:
Dynamic queries
Temporary tables
The reason is that to import the procedure EF must execute it."

Why is Entity Framework calling my stored procedure but returning an incorrect value?

I have a stored procedure that simply returns the total number of records divided by whatever value is passed in. This is to aid in pagination on a website.
However, I am using the entity framework to bind to that stored procedure and it's returning -1 for all calls to it. When I interrogate the stored procedure using SQL Management Studio, it comes back with the correct value.
My stored procedure looks like this:
CREATE PROCEDURE [dbo].[GetAuditRecordPageCount]
#Count INTEGER
AS
RETURN ((SELECT COUNT(Id) FROM AuditRecords) / #Count) + 1
And my call to the entity framework in C# is this:
int pageCount;
using (Entities entities = new Entities())
{
pageCount = entities.GetAuditRecordPageCount(count);
}
Am I correct in writing the C# code this way?
As per a request in the comments, the SQL generated by EF is:
exec [dbo].[GetAuditRecordPageCount] #Count=100
Did you tried that?
http://www.devtoolshed.com/using-stored-procedures-entity-framework-scalar-return-values
I think your procedure will look like this:
CREATE PROCEDURE [dbo].[GetAuditRecordPageCount]
#Count INTEGER
AS
declare #retVal int
set #retVal = ((SELECT COUNT(Id) FROM AuditRecords) / #Count) + 1
select #retVal
And in the c# code:
int? pageCount;
using (Entities entities = new Entities())
{
pageCount = entities.GetAuditRecordPageCount(count).SingleOrDefault();
if (pageCount.HasValue)
{
//do something here
}
else
{
}
}
Don't forget to put "Scalars: Int32" in edit function Import screen.

I'm not geting the right results from a stored procedure

I have this strored procedure that I use to get the sum of Amount from 3 tables.
The problem is that I'm using Linq to Sql and when I put this procedure on my .dbml file, it has a
ISingleResult(GetSurplusDataForConsolidationReportResult) and I can't get the sums I want.
I'm receiving an empty ReceivablesSurplus list.
Any ideas?
ALTER PROCEDURE [dbo].[GetSurplusDataForConsolidationReport]
#ID INT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT SUM(RB.[Amount])
FROM [DBO].[ReceivablesSurplus] RB
WHERE RB.[Cycle] = #ID
SELECT SUM(DL.[Amount])
FROM [DBO].[DilutionsSurplus] DL
WHERE DL.[Cycle] = #ID
SELECT SUM(AC.[Amount])
FROM [DBO].[AccountablesSurplus] AC
WHERE AC.[Cycle] = #ID
END
this is my .dbml code
[global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.GetSurplusDataForConsolidationReport")]
public ISingleResult<GetSurplusDataForConsolidationReportResult> GetSurplusDataForConsolidationReport([global::System.Data.Linq.Mapping.ParameterAttribute(Name="ID", DbType="Int")] System.Nullable<int> iD)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), iD);
return ((ISingleResult<GetSurplusDataForConsolidationReportResult>)(result.ReturnValue));
}
You should just be able to use .ToList() on the value (as ISingleResult implements IEnumerable) to the calling line of code, and then you can get at the separate result sets that are returned from the sproc.
e.g
var results = dataContext.GetSurplusDataForConsolidationReport(123).ToList<int>(); // list of sums

Categories

Resources