Saturday, October 1, 2011

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.
image
In order to add a stored procedure open up the Model Browser and right click on the Model.Store in this case NorthwindModel.Store

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

image
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
image
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);
}
else
{
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
image