Retrieving table data from stored procedure using entity structure
I am 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 query result SELECT
in typeList<CountryName>
List<CountryName> countryList = null;
using (DbEntities dbContext = new DbEntities())
{
countryList = //my code to collect the result
}
Well, I could run LINQ to SQL directly on the table, but unfortunately my requirement is to get data from a stored procedure. So how can I do this?
+3
source to share
2 answers
- You need to import the stored procedure as a function. Right-click the workspace area of your Entity model and select
Add -> Function Import
. - In the Add Import Function dialog box, enter the name that your stored procedure will be referred to in your model, for example
GetCountryListSP
, select your procedure from the dropdown list and select the return value of the procedure to beEntities
and selectCountryName
from the dropdown list. -
Then in code:
var result = db.GetCountryListSP();//Send parameters too
With this approach, you cannot return a
-1
stored procedure. Please see this for more details on stored procedure issues in Entity Framework.
+9
source to share