Using Stored Procedures in Entity Framework

Entity framework supports stored procedure. In this post I will explore how we can use stored procedures in entity framework.

I have created a Windows based application with Northwind database model(EDMX) . And have the Customer and Orders table selected.


In order to add a stored procedure open up the Model Browser and right click on the Model.Store in this case NorthwindModel.Store



And choose the required stored procedure. Next right click anywhere on the Edmx designer and choose Add > Function Import.



This will bring up the wizard for adding Function. Choose the procedure you had added in the Model Store and choose the return type. In this case Customers which is of type Entity


This step will add a function to the EntityContext class. Here is how the generated code might look like

         /// <summary>
        /// There are no comments for NorthwindModel.CustByCountry in the schema.
        /// </summary>
        public global::System.Data.Objects.ObjectResult<Customers> CustByCountry(string country)
            global::System.Data.Objects.ObjectParameter countryParameter;
            if ((country != null))
                countryParameter = new global::System.Data.Objects.ObjectParameter("Country", country);
                countryParameter = new global::System.Data.Objects.ObjectParameter("Country", typeof(string));
            return base.ExecuteFunction<Customers>("CustByCountry", countryParameter);


In my forms code I use an Object Data Source and have the following code for Forms_Load

          using (NorthwindEntities entities = new NorthwindEntities())
                this.customersBindingSource.DataSource = entities.CustByCountry("Germany");

Here is the output


Comments (5)

  1. Stored Procedure con Entity Framework

  2. A questo indirizzo è disponibile una breve spiegazione di come usare le stored procedure con l&#39; Entity

  3. Ajax2020 says:

    When i am doing fucntion import for stored proc which returns nothing ,the function is not added to EntityContext class.

    If i open .edmx file with xml editor i can see the element for my function. but it not in the EntityContext class.

    Please help…

    thnks in advance

  4. Leon Ford says:

    How do I modify an import function once created?  I if forget to specify the Entity return type, I can’t redo the Add Import Function to re-create it because it gives me a duplicate function name error.