Accessing Data from Stored Procedure with Entity Framework
This article addresses the challenge of retrieving data from a dynamic SQL stored procedure using Entity Framework 6.1.1. The goal is to populate a GridView control with the retrieved data.
The scenario involves a stored procedure called SearchProducts that accepts a search term as a parameter and returns a result set based on a dynamic SQL query. The C# code attempts to execute the stored procedure and bind the result to a GridView control.
The Problem
When the code is executed, the stored procedure works in the Database Explorer but fails in the running application, returning -1 instead of an IEnumerable DataSet. This indicates that the data is not being retrieved successfully.
The Solution
To solve this issue, it is necessary to import the stored procedure as a Function in the Entity model. Here are the steps:
In the Add Function Import dialog:
Update the C# code:
The revised code:
var db = new MyEntities(); var TEST_SEARCH_TERM = "product"; var result = db.Search_Products(TEST_SEARCH_TERM); MyGridView.DataSource = result; MyGridView.DataBind();
Explanation
Entity Framework lacks full support for stored procedure return values. Importing the stored procedure as a Function allows it to be treated as an Entity Framework method, which can handle the retrieval of data.
The above is the detailed content of How Can I Retrieve Data from a Stored Procedure Using Entity Framework and Populate a GridView?. For more information, please follow other related articles on the PHP Chinese website!