robdigm
robdigm

Reputation: 143

How to retrieve a value returned from a stored procedure using entity Framework?

I have been looking around for a suitable manner to handle this. I have a stored procedure which looks up a record from a table through the use of an ID parameter, which outputs only one column.

On the c# side of the house, I am calling the stored procedure through a DB context.

Currently, the error received is: "null" The intended result is the contents of that row.

Executed Query example

CREATE PROCEDURE [dbo].[getLog]     
@logId INT
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
SET NOCOUNT ON;
    SELECT [Logs] 
    FROM [dbo].[output]
    Where [ID]=@logId
END
GO

C# code

OutputDTO<SearchInputDTO> output = new OutputDTO<SearchInputDTO>();
            try
            {
                var getID = srequest.ID;
                var retLog = _output.getLog(getID);
                return Ok(retLog);
            }
            catch (Exception e)
            {
                ErrorHandler.HandleError("Failed to retrieve rows: ", e);
                LogManager.Log("error", Level.ERROR, "Login: " + e);
                output.Success = false;
                output.ErrorMessage = "Failed to retrieve rows.";
                output.ErrorDetails = new Dictionary<string, string>
                    {
                        { "Error", output.ErrorMessage }
                    };

                var json = new JavaScriptSerializer().Serialize(output);
                return Ok(json);
            }

Upvotes: 1

Views: 55

Answers (1)

Workaholic
Workaholic

Reputation: 93

As mentioned in the Question: you are using Entity Framework. Why you have to call stored procedure for it?

You can do it through linq

dbContext.Output.Where(x=>x.Id == logId).FirstOrDefault()

This will return you the First returned object of output table.

Hope this helps.

Upvotes: 1

Related Questions