Creating an OData Server Quickly

Windows Phone Tutorial

There are numerous ways to access data from Web Services.  To explore these we need a simple server that exposes data we can interact with from a Windows Phone Application.

To facilitate this, we’ll build an ASP.NET/MVC 3 application that uses  Entity-Framework Code-First (Magic Unicorn Edition)  on top of SQLCE4, and we’ll expose the data in a WCF Data Service using the Open Data (OData) Protocol   This can be done surprisingly quickly and is highly reusable.

We’ll start with a dead-simple model (and build from there in later postings).

Instant Server – just add code

Create a new ASP.NET / MVC 3 application and name it SimpleServer.  At the Project Template dialog, choose Internet Application.

The first task is to add the Entity Framework Code-First library with SQL  Server NuGet Compact 4.0.  This is easily accomplished with NuGet.  Open the Add Library Package dialog, click on Online/All and in the search window type EFCodeFirst.SQL – the package you need will come up as shown in the figure.

Click to install and that package and all its dependencies will be loaded into your project.  You will need to accept the licenses in the “click to accept” dialog.

Adding the Model

Right click the Models folder and add a new class named Book.  Here’s the complete source code for the Book class:

namespace SimpleServer.Models
{
    public class Book
    {
        public int ID { get; set; }
        public string ISBN { get; set; }
        public string Title { get; set; }

        public class BookContext : DbContext
        {
            public DbSet<Book> Books { get; set; }
        }
    }
}

Notice that the Book class has no attributes or special interfaces, nor any specific base class. It is a POCO and all that is needed is the Context (BookContext), which we’ll use to access the entities in the application.  The only requirement for the context is that it inherit from DbContext and hold one or more DbSet.

We need some testing data to expose from our service. The simplest way to get that into our database is to modify the CreateCeDatabaseIfNotExists class in AppStart_SQLCEEntityFramework.cs by adding some seed data to the Seed method

 protected virtual void Seed(TContext context)
 {
     var bookContext =
           context as SimpleServer.Models.Book.BookContext;
     bookContext.Books.Add( new Models.Book
     {
         ID = 1,
         ISBN = "143023816X",
         Title = "Migrating to Windows Phone"
     } );

     bookContext.Books.Add( new Models.Book
     {
         ID = 2,
         ISBN = "1430237473",
         Title = "Programming Reactive Extensions"
     } );

     bookContext.Books.Add( new Models.Book
     {
         ID = 3,
         ISBN = "0672333317",
         Title = "Teach Yourself C++ In 24 Hours"
     } );
 }

Also in SQLCEEntityFramework.cs, at the top of the file, be sure to uncomment the setInitializer and to replace the context name,

public static void Start() {
    DbDatabase.DefaultConnectionFactory =
     new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");

    DbDatabase.SetInitializer(
       new CreateCeDatabaseIfNotExists<
          SimpleServer.Models.Book.BookContext>());
}

Add a new WCF Data Service to the project (right-click the project / Add New Item / Web / WCF Data Service).  Name it BookDataService.

Open the codebehind for the service and replace the code for the class with this code that makes debugging easier by including exception details in faults and using verbose errors (remove all of this when the service is working).

[ServiceBehavior( IncludeExceptionDetailInFaults = true )]
public class BookDataService :
    DataService< SimpleServer.Models.Book.BookContext >
{
    public static void InitializeService(
        DataServiceConfiguration config)
    {
        config.SetEntitySetAccessRule(
            "*", EntitySetRights.All );
        config.DataServiceBehavior.MaxProtocolVersion =
            DataServiceProtocolVersion.V2;
        config.UseVerboseErrors = true;
    }
}

You can see the output of the service’s collection by browsing to http://localhost:[port number]/BookDataService.svc/Books

Hey! Presto! Instant OData Server.

Share

About Jesse Liberty

Jesse Liberty is a Master Consultant for Falafel Software, and has three decades of experience writing and delivering software projects. He is the author of 2 dozen books and multiple Pluralsight courses, and has been a Technical Evangelist for Telerik and for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS.
This entry was posted in Data, Essentials, Mango, Mini-Tutorial and tagged . Bookmark the permalink.

3 Responses to Creating an OData Server Quickly

  1. Johnesh says:

    Great article. oData version 3 is now available and allows use of dbContext directly.Initially one had to override the CreateDataSource method to manually get the ObjectContextto provide to the data services. http://www.microsoft.com/en-us/download/details.aspx?id=29306

  2. Vagif Abilov says:

    Are you sure WCF Data Services will be able to use DbContext-derived class directly? AFAIK, since DataService was designed prior to EF 4.1, it needs and adaptor from DbContext to ObjectContext. Luckily it’s easy to add. Here are some info on this:

    http://blogs.msdn.com/b/writingdata_services/archive/2011/06/15/entity-framework-4-1-code-first-and-wcf-data-services.aspx

    http://social.msdn.microsoft.com/Forums/en/adonetefx/thread/0c1f8425-55f4-4600-9605-a925220d5a25

  3. Pingback: Windows Azure and Cloud Computing Posts for 9/20/2011+ - Windows Azure Blog

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>