In the previous posts on entity framework, we saw some basic tutorials on programming using Entity Framework. This post is about calling a stored procedure using Entity Framework. I assume that you have idea in creating .edmx and write stored procedures in SQL server.
1) Write a stored procedure and execute it in your data base, In my case I have written a simple SP to delete the records with odd Numbered Primary Keys from a table.
2) Then Go to your application and open the .edmx file>> right click and select Update Model from database.
3) An update wizard will open. In which you can select the stored procedure that you would like to execute through Entity Framework >> Click finish.
4) Now open the model browser by right clicking the .edmx file and selecting Model browser. You will now be able to see the your stored procedure under (Second red box in model browser) yourmodel.store tree view. You will be able to see another parent tree just above that in the name of your model, traverse to Entity Container >> Function imports (first red box in the model browser).
5) Right click Function Imports and select “Add Function import“. The below wizard will open in which you need to give a name to sp and then select the SP that you want to call from your code. Provide the return parameters. if any(In my case I am not using any return type in my SP). Click “ok“.
6) Go to the fuction from where you want to execute it and call the ExecuteFunction method by passing the params as string array, if any. In the code snippet below, I have called my “DeleteOddAddress” SP.
The result for this execution returns 0 records since I do not have any odd numbered address ids in my table.
Hope you find this useful. Happy Learning Folks!!!