Create a RESTful Web Service for SQL Server using OData with Entity Framework

One of the great things about the clouds is that it makes existing good technology even better and in the case of the Azure stack, also much more simpler. One example that came to mind this week was Entity Framework after reading that it now works with CosmosDB, albeit still in beta and for the Core version only. For those not familiar, “Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.” Put another way, it saves us developers heaps of time and a must have skill if you code in .Net and work with data.

Before diving straight into EF with CosmosDB, I thought it would be an idea to refresh my memory on EF using relational since it’s been years since I’ve touched EF. As I was reminded just how powerful yet simple this was, I also decided to write a short blog about this. To make it more interesting I also decided to build a web service using Windows Communication Foundations (WCF) specifically for SQL Server. While SQL is the native platform, EF and WCF also works with Oracle and Postgres. You simply need to install the necessary drivers.

So without further ado, lets get started. First off, create a new ASP.Net Web Application in Visual Studio.

RESTful Web Services- Sam Tran

For the type of web application, select Empty and ensure to leave all the checkbox unticked to avoid reconfiguring later on. Note especially I’m keeping the default ‘No Authentication’ settings to keep things simple. Authentication is a complex and technical area that would require several books to cover.

Click OK.

RESTful Web Services- Sam Tran

In the object explorer, right click the project and select Add New.

RESTful Web Services- Sam Tran

The next screenshot assumes you already have EF installed, Select ADO NET Entity Data Model and give your model a meaningful name. As the source database in this case will be the AdventureWorks DW database, I’m just naming it that. If you don’t already have EF installed, you can download this through Nuget

RESTful Web Services- Sam Tran

Select EF Designer from Database as we’re working off an existing database.

RESTful Web Services- Sam Tran

Provide the connection details. Note I’m providing connections to an Azure SQL database as I plan to deploy the app/web services to Azure in the cloud later and this makes things easier. You could well select an on-prem database though that will require configuring a gateway.

RESTful Web Services- Sam Tran

As this is just a demo and we want to keep it simple, just select ‘Yes’ in the checkbox below.

RESTful Web Services- Sam Tran

Select the objects you want exposed in the API. Here I randomly picked a few tables and two stored procs I wrote specifically for this demo. One of the procs simply returns a table while the other has a parameter to filer out the results which will be used to illustrate passing parameters.

RESTful Web Services- Sam Tran

Once you hit finish above, your model and corresponding mapping will be created as seen below.

RESTful Web Services- Sam Tran

Next up, you need to create an OData Service which is part of the Windows Communications Foundations. To add OData, simply right click your project in the Solutions Explorer and select “Add New Item” as you did to add Entity Framework earlier only this time, pick WCF Data Services as seen below.  If you can’t see this here, you need to install it via NuGet. Give your service a meaningful name here as this will form part of the base URL for your web services.

WCF Odat Services Sam Tran

As with EF which automatically created a whole lot of code for you earlier, WCF OData will also create the basic scaffolding needed. For the really basic web services we’re about to create, all that needs to be done now is to update one line of code within your class. As seen below, you need to replace the ‘Todo” line in blue with your data source class.

WCF OData Sam Tran

For us, it is simply “AdventureWorksDWEntities” as seen below. If you’re new to EF, just start typing the word “entities..” and intellisense will automatically bring up the available values. You’ll also notice I’ve uncommented and updated the two lines for configuration. This is to give our services more permissions.

With the codes updated, we’re all ready. Just  hit debug and our web services is ready for use and testing (locally).

WCF OData- Sam Tran

This will launch a web browser like the one below. The contents of this will depend on the objects you selected earlier (tables, views). These are the objects already available in our web services. You’ll notice our procs are not shown. This is expected but they’re also not available just yet and require some minor coding to expose them (for security reasons). All the other tables and views are ready for consumption.

WebServices

And to confirm our procs have been imported and mapped, we can view this in the Model Browser (they’re just not exposed, yet).

ModelBrowser

Lets test one of the endpoints locally using just the browser. To do this, simply append the name of your table to the base URL so that it looks something like this:

http://localhost:52354/WcfDataService.svc/DimProducts

This should bring back all the data from the DimProducts table in xml, the default format for OData and with it, confirmation our web services is working.

base.PNG

Now we’re ready to deploy our app to Azure and make our data, it’s models and associated business rules available across the globe. With just a few clicks, we can share as little or as much data as we like with our overseas subsidiaries and/or clients. I won’t go into details of deployment as that’s another topic but it is fairly straightforward, just follow the normal process of deployment. I will show this below to show you can deploy it to an App Service or Azure Virtual Machine. I selected App Service as that’s faster and easier to manage.

Publish

Before deploying the app, I will update some codes so as to expose the endpoints for the stored procs. Mappings and other scaffolds were generated by EF and WCF for the procs but for security reason, you need to do the rest manually, unlike tables and views. To expose the procs, just add the two methods you see below and note the name of the procs will form part of your URL, just like the tables and views. To call the procs, your URL will look something like this:  http://restsam.azurewebsites.net/WcfDataService.svc/SpGetProduct 

If you don’t intend on exposing your procs, you can skip this part.

StoreProc

With the app deployed, our web services is ready and in the clouds, ready for consumption across the globe. Lets test it with some front end clients. First off, we’ll use Linqpad, my favourite toy. Simply add a WCF Data Services connection (though there are other ways to use Linqpad without these drivers).

LinqpadWCF

For URI, just add your base URL, hit Test and OK if connection made. You’ll recall we didn’t use authentications earlier to keep things simple so name and password is not needed.

lp

With connection made, you can start coding in C#, VB.NET or simply using LINQ.

Linqpad10

Next up, we’ll use Powershell. Note how little coding needed.

Powershell REST API OData Sam Tran

And with Postman- this time to call our stored proc SpGetEmp with the (first) name parameter of “David”.

proc

Tableau also has OData connectors. To use these, just add the full URL for your resource like this below for DimProducts (recall convention is base URL+name of object)

Tableau

Tableau2

Same with PowerBI.

PowerBIPowerBI2

And my other favourite tool, SSIS. You just need to install the Odata drivers for SSIS. These are available in the SQL Service 2014 Feature Pack.

SSISSSIS Odata WCF Sam Tran

Other Configurations: What if I want JSON instead of XML or if I only want a subset of the data. No problems, like any REST API, just state so within your payload. To limit the load, just add the $top parameter and its value and to get JSON, just add  Accept headers with the value “application/json” like this below. As expected, we’re only getting two rows back and in JSON format for this call.

Postman WCF OData Sam Tran

And doing the same thing via a browser..

JSON

So there you go, something extremely powerful and easy at the same time that can be built in minutes with just a few lines of code. But don’t let this fool you though because both WCF and Entity Framework have much much more to offer. For those that just want a public OData services to play with, try: https://services.odata.org/V3/Northwind/Northwind.svc/

Happy coding.

Sam


Leave a Reply