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.
Install Below NuGet packages
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; }
}
}
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!;
}
}
Now, update the appsetting.json to configure connection string.
"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:
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:
As the next step, run the following command in the PMC:
Update-Database
You will see the newly created database as below:
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
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;
}
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;
}
Go to Developer PowerShell or Command Prompt and execute the below command to test POST method.
Go to Postman and Create New Http Request and execute the POST Method.
http://localhost:<portnumber>/api/movies
Now, Goto SSMS and execute the below to see the added movie.
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;
}
We can test the application by calling the two endpoints from Postman as follows:
https://localhost:{port}/api/movies
https://localhost:{port}/api/movies/{id}
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;
}
and test the Update method using Postman to update any value.
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();
}
Execute the following command in Postman to test the Delete method.
We will continue to run this application using docker file in the next part. You can find the full project in this GitHub repository
Top comments (0)