In this post I'm going to provide complete instructions on how to generate a RESTful web service starting with the Northwind sample database. The web service will be able to handle SData or OData URLs/Queries.
With Visual Studio (VS) it's easy to build a RESTful web service starting Model & Database and adding support for SData URLs is easy too.
I'm going to do this with Visual Studio 11 Beta, Entity Framework (EF) 5 and EF 5.x DbContext Generator for C#. I'll generate my Model from SQL Server and the Northwind sample database.
Video TutorialI provide instructions below the video if you prefer. The Video will show:
- Creating the MVC .NET 4 Web API project from the Northwind database
- Routes for handling SData Single and Collection URLs
- Referencing the SDataTransformHandler which handles complex SData queries
Instructions for generating a RESTful web service from the Northwind Demo database.
Create Web API project in VS
Add database connection
Add model from database
Generate the code from the model
Exception Details: System.Xml.XmlException: You must write an attribute 'type'='object' after writing the attribute with local name '__type'.
Generate Controller for each the Entity
- Right Click “Controllers” folder and “Add Controller”
- The Add Controller Wizard will popup enter the following:
- Specify Controller name that matches target Entity, E.G: "CustomerController" for the Customer model class
- Template: drop box select “API controller with empty read/write actions".
- Model class: Select the Model class, e.g. "Customer"
- Data context class: Select the DbContext created in step 3 of Generate the code from the model instructions above. E.G: "NorthwindEntities"
Add logic to the controller class to read data
"Exception Details: System.Xml.XmlException: You must write an attribute 'type'='object' after writing the attribute with local name '__type'."
It’s because you did not remove the “virtual” keyword from the generated entities classes as indicated above. This is a bug in MS's framework.