Home > .NET, MVC, OData, Vs2013 > OData services

OData services


My previous post is half the story.

The original intent was to use Entity Framework and build an WCF data service, but with the latest EF 6.1.0 it seems that is no more possible.

Microsoft is now strongly oriented to the new OData religion: i discovered that there is a NUGet project for a bridge between WCF and EF6 in a alpha stage, and it seems abandoned from months.

I tried, but it installs an EF6 prerelease, and in every case i was not able to obtain something of working.

In my previous post i was able to create an EF model, and then i added an WCF Data Service 5.6.

But it was not working , trying to launch the .svc file i got

“The server encountered an error processing the request. See server logs for more details.”

I ended up with this code:

namespace NorthwindWeb
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    public class NorthwindCustomers : DataService<NorthwindEntities1>
        public static void InitializeService(DataServiceConfiguration config)
            config.UseVerboseErrors = true;
            config.SetEntitySetAccessRule("Customers", EntitySetRights.AllRead);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;

The ServiceBehavior decoration gives detailed error infos , which was:

“The server encountered an error processing the request. The exception message is ‘Expression of type ‘System.Data.Entity.Core.Objects.ObjectContext’ cannot be used for return type ‘System.Data.Objects.ObjectContext”

It seems that i should use EntityFrameworkDataService<NorthwindEntities1> instead of DataService, but this object is apparently not available in EF6 object model or somewhere else, and i’m not the best WCF/EF expert.

I’m thinking to the ones (also me) that had written a lot of WCF code using EF…they should rewrite all? or the projects needs to be “closed”, no more NuGet updates ?

This is another case where “googling” i find that i’m not alone.

Ok , waiting for the next Microsoft change of mind (“throw away OData: is old, unsecure, blah blah.. now there is <new buzzword>”) i wrote the OData web service with Web API…sometimes i envy the COBOL programmers that are maintaining ancient software where the screens are painted with | and -.

So from Visual Studio 2013 new project ->ASP.NET Web Application

Then in the next wizard step choose the Empty template but add Web API:

This is the moment of adding via NuGet (TOOLS->NuGet Package Manager->Manage NuGet packages for Solution.. the Entity Framework and OData.


Now is recommended to clic on Updates and update all of the NuGet components:

Now if we want to add an Data Model there is still the trouble described in the previous post; so copy the sample connection string in web.config (also from the mentioned previous post) changing the name , data source, initial catalog and so on.

We still use Northwind as sample, so we add to the solution an ADO .NET Entity Data Model that in our sample we call NorthwindModel.edmx

In order to avoid mistakes , is better to leave checked the creation of a new connection string, that will be the one used:

In this sample we still use only the Customers table

With a Model Namespace = NorthwindModel

Do a Build->Rebuild all, otherwise in the next step Visual Studio complains about an error.

In the automatically generated Controllers folder (in the Visual Studio solution) right clic and add a controller:

We add “Web API2 OData with actions, using Entity Framework”.

In the next step by simply clicking on the drop downs and writing “CustomersEntity” in Controller name we can set the controller as in figure:

In the Controllers folder now we have a CustomersEntityController.cs class: Visual Studio and his template engine is so gently that is generated also an sample of code:

The commented code must be copied in WebApiConfig.cs class under the App_Start folder, so at the end we have

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.OData.Builder;
using NorthwindSvc;
namespace NorthwindSvc
    public static class WebApiConfig
        public static void Register(HttpConfiguration config)
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());

Ok, now we can launch the site.

Tipically this does nothing, complaining that a default document is not configured for the requested URL, and directory browsing is not enabled on the server.

But in CustomersEntityController.cs we can see examples of calling the web service, so if we add /odata/CustomersEntity to the browser address (for example http://localhost:11775/odata/CustomersEntity)

we get an JSON file with the records of the Customers table:

This with Google Chrome, Internet Explorer requires to download the JSON file.

Observing the generated code we can read

// GET odata/CustomersEntity(5)
public SingleResult<Customers> GetCustomers([FromODataUri] string key)
    return SingleResult.Create(db.Customers.Where(customers => customers.CustomerID == key));

This means that we can write /odata/CustomersEntity(‘ALFKI’) and we get only the corresponding record.

With OData are coming for free many interesting features regarding the querystring

For example we can write

That is we filter our data for Country = Mexico and we need only the company name and the fax; the result:

The condition could be complex, for example we can specify &filter=Country eq ‘Mexico’ and CustomerID eq ‘ANTON’

A reference of the OData query options at these addresses:



Categories: .NET, MVC, OData, Vs2013
%d bloggers like this: