React and .NET Core 6.0 Sample Project with Docker - Part 1
Tags: api, c
Published: 2022-10-15 09:15:57

This article will explain about the CRUD (Create ,Read ,Update and Delete) operations in ASP.NET Core 6.0 WEP API using Entity Framework Core Code First approach.

The sections of this post will be as follows:

Creating a Web API Project
Adding a Model
Adding a Database Context
Creating Database with Migrations
Creating API Controller and Methods

We need the following tools installed on our computer:

Visual Studio 2022
.NET 6.0 SDK
Microsoft SQL Server Express
Postman

If you are ready, let’s get started.

**Create ASP.NET Core Web API Project**
   Open Visual studio -> New Project -> ASP.NET Core Web API.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8gljmem23a6c27wt99yv.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/slff7nyzafd1yiwj14lw.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bmkr8ct7sl8vsprdo070.png)

**Install Below NuGet packages**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l67vxg3r0oygunjk897c.png)

**Adding a Model**
   
Now, we will implement our data model class.

In Solution Explorer, right-click the project. Select Add -> New Folder and name the folder Models.

Then right-click the Models folder and select Add->Class. Name the class Movie.cs and click Add.

Next, add the following properties to the class:

```c#
namespace MoviesAPI.Models
{
    public class Movie
    {
        public Guid? Id { get; set; }

        public string? Title { get; set; }

        public string? MovieLanguage { get; set; }

        public string? ReleaseYear { get; set; }

        public string? OTT { get; set; }

    }
}
```
**Adding a Database Context**

Now, right-click the Models folder and select Add ->Class. Name the class MovieContext and click Add. Then add the following code to the class:

```c#
using Microsoft.EntityFrameworkCore;

namespace MoviesAPI.Models
{
    public class MovieContext:DbContext
    {
        public MovieContext(DbContextOptions<MovieContext> options):base(options)
        {

        }

        public DbSet<Movie> MoviesList { get; set; } = null!;
    }
}
```
Now, update the appsetting.json  to configure connection string.

```c#
"ConnectionStrings": {
    "MovieConnection": "Data Source=ServerName;Initial Catalog=Movies;Integrated Security=true"
  }
```

Now, we will register our database context to the built-in IOC container. Add the following code to Program.cs:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yj919nmi0tyienqxs8et.png)



**Creating Database with Migrations**

Now, we will create the database using the EF Core Migrations feature.

Open Tools -> NuGet Package Manager > Package Manager Consoleand run the following command in the PMC:

`Add-Migration Initial`

After running the command, a migration file is created under the Migrations folder:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7nxd6pa2f8itu8bsmth8.png)

As the next step, run the following command in the PMC:

`Update-Database`

You will see the newly created database as below:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nyc2gfkcblrufbm4ewp5.png)

**Creating API Controller and Methods**

Let's add Movies API Controller and test the CRUD Methods.

Right-click on the Controller folder and select Add -> Controller.. and then select API Controller - Empty as below:

Name : MoviesController.cs

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q8bdih0cy47mn0kby64b.png)

Add the bellow code to the MoviesContoller file.This will inject the database context through the constructor of the controller.

```c#
private readonly MovieContext _movieContext;
        public MoviesController(MovieContext movieContext)
        {
            _movieContext = movieContext;
        }
```

Now, we will add CRUD (create, read, update, and delete) action methods to the controller. Let’s start with the POST methods.

**POST Method:**

Add the following code in MoviesController.cs

```c#
[HttpPost]
        public async Task<ActionResult<Movie>> AddMovie(Movie movie)
        {
            if (_movieContext == null)
            {
                return NotFound();
            }

            _movieContext.MoviesList.Add(movie);

            await _movieContext.SaveChangesAsync();

            return movie;
        }
```

Go to Developer PowerShell or Command Prompt and execute the below command to test POST method.

`dotnet build`
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j3axriu7jvmjqpuyv6ul.png)

`dotnet run`
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d9azibeh2wxdodovdq3h.png)

Go to Postman and Create New Http Request and execute the POST Method.

`http://localhost:<portnumber>/api/movies`



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5gaj536982r7xzqhber3.png)

Now, Goto SSMS and execute the below to see the added movie.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/konuc9t3ax2g9cp93rp5.png)

Similarly add few more movies to the database by executing POST method.

**GET Method:**

Add the following code to the MoviesController.cs 

```c#
//GET : api/movies
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Movie>>> GetMovies()
        {
            if(_movieContext == null)
            {
                return NotFound();
            }
            return await _movieContext.MoviesList.ToListAsync();
        }

        //GET : api/movies/id
        [HttpGet("{id}")]
        public async Task<ActionResult<Movie>> GetMovies(Guid id)
        {
            if (_movieContext == null)
            {
                return NotFound();
            }

            var movie = await _movieContext.MoviesList.FindAsync(id);
            if (movie == null)
            {
                return NotFound();
            }
            return movie;
        }
```
We can test the application by calling the two endpoints from Postman as follows:

https://localhost:{port}/api/movies
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fws0k2u13651771wkc7j.png)
https://localhost:{port}/api/movies/{id}
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3cicueaue8xrov1at6fu.png)

**UPDATE Method:**

Add the following code to the MoviesController:

```c#
 [HttpPut("{id}")]
        public async Task<ActionResult<Movie>> UpdateMovie(Guid id, Movie movie)
        {
            if (movie.Id != id)
            {
                return BadRequest();
            }

            _movieContext.Entry(movie).State = EntityState.Modified;

            await _movieContext.SaveChangesAsync();

            var updatedMovie = _movieContext.MoviesList.FirstOrDefaultAsync(x => x.Id == id);

            return movie;
        }
```
and test the Update method using Postman to update any value.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sztgcp34ebmev3936yoh.png)

**DELETE Method:**

Add the following code to the MoviesController.cs 

```c#
    [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteMovie(Guid id)
        {
            var movie = await _movieContext.MoviesList.FindAsync(id);

            if (movie == null) return NotFound();

            _movieContext.MoviesList.Remove(movie);

            await _movieContext.SaveChangesAsync();

            return NoContent();

        }
```

Execute the following command in Postman to test the Delete method.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4nyvkwlz0t8ujidtviso.png)

We will continue to run this application using docker file in the next part. You can find the full project in this [GitHub repository](https://github.com/jayavardhan5555/MoviesAPI)