In my last article, I described how to use Visual Studio to create and deploy an Azure Mobile Service with server-side code written in a .NET language. I chose C# for that example. In this article, we will walk through the boilerplate C# code generated when you create a new Azure Mobile Services project.
Figure 1 shows the newly-created Azure Mobile Services project in Visual Studio’s Solution Explorer
Let’s go through the key parts of the code.
The Application_Start code runs at the very beginning of the application so any startup code goes here. In this case, we call the static method WebApiConfig.Register (Listing 1).
Let's take a look at the Register method in the WebApiConfig class. WebApiConfig.cs is in App_Start folder.
This project uses the Entity Framework to interact read and write data. The most important line of the Register method (Listing 2) is
which initializes Entity Framework settings. The new MobileServiceInitializer is found in the same file and it has the ability to seed the sample TodoItem table with a couple records (Listing 3)
Next, we'll look at the TodoItem class (Listing 4), which can be found in DataObjects folder. This is the data model and will. It has 2 explicit properties - Text: the text of a Task that we need to complete; and Complete: a flag indicated whether or not we have completed this task. This object will will map to columns in the TodoItem table.
We don't need to explicitly provide an ID property because the class inherits this property from the EntityData class.
This is a Context used to manage database updates and retrievals via Entity Framework. It knows where to connect to the database and what model to send to the database. The Controller class will instantiate this to interact with the database table.
TodoItemController is the main controller class that maps HTTP Verbs (POST, PATCH, GET, and DELETE) to specific actions. It inherits from the TableController class, which has an IDomainManager named DomainManager that is used to retrieve and update data using Entity Framework. All the controller methods need to do is to call TableController methods, such as Lookup, UpdateAsync, InsertAsync, and DeleteAsync.
For example, if a client sends a request to our mobile service’s HTTP endpoint with the POST verb, the routing engine will run the PostTodItem method in TodoItemController (Listing 5).
To add business logic to your service, you will add code to the Controller methods (GetAllTodoItems, GetTodoItem, PatchTodoItem, PostTodoItem, and DeleteTodoItem.)
In this article, we covered the code that is automatically generated in a C# Azure Mobile Service.