Getting started with Web API

In this article, I will show you how to create a simple C# Web API using ASP.NET and Entity Framework code-first approach.

Project

Create a new ASP.NET project and select Azure API app template. Check “Host in Cloud” option.

Models

Create a new class library and data models that suit your project. In this case, I’m going to create two models. The first model will contain information about an article.

The second model will contain information about an article’s source and also a collection of all its articles.

Controllers

Build the project, right-click on a “Controllers” folder and then click “Add” -> “Controller”. Select Web API 2 Controller with actions using Entity Framework.

  1. Select Model class
  2. Click “+” to add new Data Context class if not exist
  3. Check “Create async controller actions”
  4.  Click “Add”
  5. Build project
  6. Repeat steps 1-5 for each model.

Database

Open Package Manager Console and run commands:

Notice that Migrations/Configuration.cs class had been created. There is a method called Seed, and it’s used to insert or update data during the initialization process of a database.

Now, run:

and:

..your database, has been successfully created!

Publishing API

Right-click on API project, and click “Publish”. Validate your server connection and click “Publish”.

Swagger

In “App_Start/SwaggerConfig.cs” uncomment:

Now add /swagger to your API address to access automatically generated documentation with an ability to process client calls against your API.

Data Transfer Objects

As you can see, we want to achieve “One-to-Many” relationship, where one source can have multiple articles. However, we also need to display “Source” property in each article, what will cause an infinite loop. For this reason, we have to create new models called Data Transfer Objects, which will contain only properties that we want to appear in produced JSON file.

So, if we want to retrieve all sources, we can create new Data Transfer Object without collection of its articles or with a collection of article data transfer objects.

Conclusion

Unfortunately, casting data transfer objects manually every single time is not the best solution when you need to have multiple DTOs of your model. But…stay tuned for the next article, where I will discuss an option how to use automapping solution.

Leave a Reply