Build a Simple CRUD App with Angular 8 and ASP.NET Core 2.2 - part 1 - back-end
Tags: dotnet, angular
Published: 2019-09-18 08:31:30

## Part 1 - back-end with ASP.NET Core 2.2 and Entity Framework Core

Let’s take a look at how to build a CRUD web app using ASP.NET Core 2.2, Entity Framework Core, and Angular 8. This is part 1 where we focus on the back-end.

 [Part 2 is here - Angular 8 app with REST API](https://dev.to/dileno/build-an-angular-8-app-with-rest-api-and-asp-net-core-2-2-part-2-46ap) 

We’ll have a REST API in the back-end and the Angular app on the front-end.

The basic CRUD app will be a blog, where we can **C**reate, **R**ead, **U**pdate, and **D**elete blog posts.

**[Github repo is here: Angular 8 blog app tutorial using .NET Core 2.2 and Entity Framework back-end](https://github.com/dileno/Blog-tutorial-Angular-8-.NET-Core-2.2-CRUD)**

## Prerequisites

* [.NET Core 2.2 SDK](https://dotnet.microsoft.com/download)

* [Visual Studio 2019](https://visualstudio.microsoft.com/vs/)

For the Angular front-end we'll also use:

* [VS Code](https://code.visualstudio.com/)

* [Node.js](https://nodejs.org/en/)

* [Angular CLI](https://cli.angular.io/)

Make sure above are installed. We will use Visual Studio 2019 for the back-end and VS Code for the front-end. You can however use only Visual Studio 2019 if you want to.

*As of Sept 15th, there are previews of .NET Core 3 that work with previews of Visual Studio 2019. However, in this tutorial we won’t use any previews and only use fully released versions of .NET Core 2 and Visual Studio 2019.*

## Create ASP.NET Core 2.2 REST API

In Visual Studio 2019, create a new project and choose ASP.NET Core Web Application. Name our project (Blog). Then choose .ASP.NET Core 2.2 version and the API template:

![Create a new ASP.NET Core Web Application prompt](https://thepracticaldev.s3.amazonaws.com/i/sgoh4c7tiz8kv0ugusnb.png)

## Add models and Entity Framework Database Context

Next up, let’s create a folder called Models, and then add a class file called **BlogPost.cs**. Make sure to import necessary namespaces.

{% gist https://gist.github.com/dileno/aec0a5d8e46fd60d08fbee94686ece29 %}

Then create an API controller — right click the Controllers folder, choose Add -> Controller. Then choose **API controller with actions, using Entity Framework**.

* Choose BlogPost as Model class.

* Under Data context class, press the + button and call the context BlogPostsContext.

![Add API controller with actions prompt](https://thepracticaldev.s3.amazonaws.com/i/fav08erbc0dgmj9j8z6v.png)

When you press Add, Visual Studio will add the necessary NuGet packages and create a new database context, BlogPostContext, in the Data folder. You will also have the BlogPostsController created for you, filled with lots of API methods.

The contents of **BlogPostsContext.cs**:
 
{% gist https://gist.github.com/dileno/830fe1b579de0ddbedbd37ebc5c77f88 %}

The contents of newly created **BlogPostsController.cs**, our ApiController:

{% gist https://gist.github.com/dileno/0c587170a6730247bba3980812248815 %}

This is fully working code, with route configuration, all CRUD operations and correct HTTP verbs using annotations (HttpPost, HttpGet, HttpPut, HttpDelete). We also force our API to serve JSON, using the `[Produces("application/json")]` filter.

We’re following the best practices for REST APIs, as we use GET for listing data, POST for adding new data, PUT for updating existing data, and DELETE for deleting data.

Note that the BlogPostContext is **dependency injected**. This context is used to perform all actions needed for our app’s back-end.

We can however improve this a little bit, using the Repository design pattern to create a data repository, and inject it.

## Create a data repository

Our existing code works, however as applications grow, it’s better to split the logic into different layers:

* Data layer with the data repository that communicates with the database.

* Service layer with services used to process logic and data layer communication.

* Presentation layer with only the API controller.

For our application, we will have an API controller which communicates with the data repository. Let’s create the repository.

Right click the Data folder and create a new interface called IDataRepository. Copy and paste this code into IDataRepository.cs:

{% gist https://gist.github.com/dileno/66280843b4200222f19700b6b7bf673c %}

Then right click the Data folder again and create a new class called DataRepository. Copy and paste this code into **DataRepository.cs**:

{% gist https://gist.github.com/dileno/5b74095e49b6ee3c3cf91921d0916e85 %}

As you can see, we have dependency injected the BlogPostContext into our DataRepository class.

## Update BlogPostsController to use the data repository

Replace the code in BlogPostsController with the following:

{% gist https://gist.github.com/dileno/eabc1a53de43ae6a1b42ff8981a61410 %}

You can see the data repository in action in the `PutBlogPost`, `PostBlogPost` and `DeleteBlogPost` methods, like this:

{% gist https://gist.github.com/dileno/d3ce9210d8c522fc8354a95a40bf80a7 %}

We however choose to keep our dependency on BlogPostsContext in the controller, using both the context and data repository.

## CORS in app configuration

In **Startup.cs**, you already can see some configuration — our app will use MVC and have a db context for instance. Update the ConfigureServices method to look like this:

{% gist https://gist.github.com/dileno/665d3027909c7a36f9c2cb76c352bab7 %}

Since we’re going to call our REST API from JavaScript, we need to enable CORS. We will use a default policy.

Also, we register our DataRepository here.

Make sure to import necessary namespaces.

Note that we’ve commented out `services.AddSpaStaticFiles()`. We will uncomment this when we’ve created the Angular application, but we’re not there yet.

Then update the Configure method to look like this:

{% gist https://gist.github.com/dileno/b2b553c5cb4fa330b4bd88f277a52f8e %}

`UseCors` must come before `UseMvc` here. Don’t forget to import the necessary namespaces.

We’ve commented out SPA specific configuration here. We will uncomment `app.UseSpaStaticFiles()` and `app.UseSpa()` later, when we’ve created our Angular application.

Let’s also update **launchSettings.json** to set `launchUrl` to empty in two places:

`"launchUrl": “”`

Also delete **ValuesController.cs** in the Controllers folder.

## Setup migrations and create the database

We’re almost there!

Now that we have the BlogPostsContext and use the code first approach for Entity Framework, it’s time to setup migrations. First, let’s take a look at the database connection string in **appSettings.json**.

The connection string was created for us earlier and the app will use SQL Server Express LocalDb. You can, of course, use your own instance of SQL Server instead, just make sure the connection string is correct!

{% gist https://gist.github.com/dileno/976302990ae6a8b4347311afc1213967 %}

To enable migrations, open the Package Manager Console (Tools->NuGet Package Manager->Package Manager Console) and run this command:

`Add-Migration Initial`

We’ll get this message back:

```
Microsoft.EntityFrameworkCore.Infrastructure[10403]

Entity Framework Core 2.2.6-servicing-10079 initialized 'BlogPostsContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None

To undo this action, use Remove-Migration.
```

Perfect! A Migrations folder is created with your Entity Framework migrations, which will contain changes to the Entity Framework model. We have one migration file, named something like **20190912150055_Initial.cs**

In this file, we have the `Up` and `Down` methods, which will upgrade and downgrade the database to the next or previous version.

To create the database, we now have to execute the following command in the Package Manager Console:

`Update-Database`

Let’s open the SQL Server Object Explorer (View -> SQL Server Object Explorer). We now have this:

![SQL Server Object Explorer view](https://thepracticaldev.s3.amazonaws.com/i/6rkg4z2lc6o2lsbfxs4n.png)

Remember, if you make any changes to the data model, you need to use the `Add-Migration YourMigrationName` and `Update-Database` commands to push changes to the database.

## Try the API

Press F5 in Visual Studio to start the application. On localhost, browse to `/api/blogposts` which should return an empty JSON string. You can now use [Postman](https://www.getpostman.com/) to create a new blog post.

Here’s the JSON to post:

```
{
  "dt": "2019-09-12T18:18:02.190Z",
  "creator": "Martin",
  "title": "Test",
  "body": "Testing"
}
```

In Postman, make sure the API URL is correct and POST is used as the http verb. Fill in above JSON in the editor (choose raw) and choose JSON (application/json) before you press Send. The request and returned body result should look like this:

![Postman API POST request with body result](https://thepracticaldev.s3.amazonaws.com/i/9b8d48tprno9o0elv3ah.png)

And if you change http verb from POST to GET, you’ll now get this result:

![Postman GET body result](https://thepracticaldev.s3.amazonaws.com/i/oj9rc9xl4qno6gwgb6qm.png)

Our API is up and running!

Now on to our Angular 8 front-end app. Here's part 2 of the tutorial. [Part 2 is here - Angular 8 app with REST API](https://dev.to/dileno/build-an-angular-8-app-with-rest-api-and-asp-net-core-2-2-part-2-46ap)