api |c

React and .NET Core 6.0 Sample Project with Docker - Part 1

jayavardhan5555

Jayavardhan Reddy J

Posted on October 15, 2022

React and .NET Core 6.0 Sample Project with Docker - Part 1

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

Image description

Image description

Install Below NuGet packages

Image description

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:

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; }

    }
}
Enter fullscreen mode Exit fullscreen mode

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:

using Microsoft.EntityFrameworkCore;

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

        }

        public DbSet<Movie> MoviesList { get; set; } = null!;
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, update the appsetting.json to configure connection string.

"ConnectionStrings": {
    "MovieConnection": "Data Source=ServerName;Initial Catalog=Movies;Integrated Security=true"
  }
Enter fullscreen mode Exit fullscreen mode

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

Image description

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

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

Update-Database

You will see the newly created database as below:

Image description

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

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

private readonly MovieContext _movieContext;
        public MoviesController(MovieContext movieContext)
        {
            _movieContext = movieContext;
        }
Enter fullscreen mode Exit fullscreen mode

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

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

            _movieContext.MoviesList.Add(movie);

            await _movieContext.SaveChangesAsync();

            return movie;
        }
Enter fullscreen mode Exit fullscreen mode

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

dotnet build
Image description

dotnet run
Image description

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

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

Image description

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

Image description

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

GET Method:

Add the following code to the MoviesController.cs

//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;
        }
Enter fullscreen mode Exit fullscreen mode

We can test the application by calling the two endpoints from Postman as follows:

https://localhost:{port}/api/movies
Image description
https://localhost:{port}/api/movies/{id}
Image description

UPDATE Method:

Add the following code to the MoviesController:

 [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;
        }
Enter fullscreen mode Exit fullscreen mode

and test the Update method using Postman to update any value.

Image description

DELETE Method:

Add the following code to the MoviesController.cs

    [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();

        }
Enter fullscreen mode Exit fullscreen mode

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

Image description

We will continue to run this application using docker file in the next part. You can find the full project in this GitHub repository

💖 💪 🙅 🚩
jayavardhan5555
Jayavardhan Reddy J

Posted on October 15, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related