Tuesday, April 26, 2011

Stored Procedure in WCF Data Service

In this article we will explore, how could we use Stored Procedure with WCF Data Service?
You can read Introduction to WCF Data service and ODATA here
To use Stored Procedure, at time of creation of Data Model, select Stored Procedure as part of Data Model.

Now open EDMX file and right click on that. Select Add and then select Function Import.
Popup window will be open.
  1. Give Function import name
  2. Choose Stored procedure from drop down
  3. Choose the Entity type Stored Procedure is returning.
Stored Procedure we are selecting is GetStudentGrades and it is returning one or more entities of StudentGrade.
After clicking OK you can see columns are mapped
You can see in model browser that GetStudentGrades has been listed in Function Imports section and it is having one input parameter StudentD.
We can see now that Stored Procedure has been mapped to Entity model and can be exposed as WCF Data Service.
Next step we need to create a function in DataService class. This function will return list of entities.Client will call this function to execute Stored Procedure.

[WebGet]
public List<StudentGrade> GetStudentGrade(string studentId)
{
    SchoolEntities entities = new SchoolEntities();
    return entities.GetStudentGrades(Convert.ToInt32(studentId)).ToList();
}