Adding Stored Procedures that Retrieve Entities

Although you can use LINQ to retrieve entities and allow the Entity Framework to automatically create insert, update, and delete statements for manipulating entities, you may prefer to use stored procedures instead. You may already have stored procedures that you would like to use, or your company may prohibit sending dynamic SQL statements to the database (which is what the Entity Framework ultimately does). This section shows you how to add stored procedures to an Entity Data Model for retrieving, inserting, updating and deleting business entities.

Adding a Stored Procedure that Retrieves One or More Entities

  1. First, you must add the stored procedure to the Entity Data Model. To do this, right-click on the design surface of the Entity Data Model and select Update Model from Database... from the shortcut menu. This launches the Update Wizard. Go to the Add tab and select the stored procedure(s) you want to add, then click the Finish button:


    Note: You will not see any difference in the Entity Data Model. However, behind the scenes, the stored procedure has been added to the SSDL section of the model file as a function element. You have to perform another step to implement the stored procedure so it can be used from your business object code.


  2. Right-click the background of the Entity Data Model's design surface and select Model Browser from the shortcut menu. Expand the Stored Procedures node and you should see the stored procedure you just added:

  3. Right-click the stored procedure in the Model Browser and select Add Function Import from the shortcut menu. In the Add Function Import dialog box, the name of the function defaults to the same name as the stored procedure (a nice feature if you don't want to change your existing code). However, under Return Type you should select the Entities radio button and select the type of entity returned from the stored procedure (one of the rules of the Entity Framework is that you must have declared an entity that exactly matches the return type of the stored procedure):

  4. Click OK to import the function.

Again, you won't see any change in the Entity Data Model itself, but this new function is added as a method to the Object Context class and it can be called directly in your code.


© (c) 2026 Oak Leaf Enterprises, Inc., 1996-2026 • Updated: 04/26/18
Comment or report problem with topic