This article will explain 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 -> Search with 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 as Movie.cs and click on 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 and add CORS policy to ,so that UI can access web API requests. 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 above commands, migration files will be created under the Migrations folder:
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/CREATE Method
Add the following code in the MoviesController.cs
The HTTP POST request is used to create a new record in the data source in the RESTful architecture.
[HttpPost]
public async Task<ActionResult<Movie>> AddMovie(Movie movie)
{
if (_movieContext == null)
{
return NotFound();
}
_movieContext.MoviesList.Add(movie);
await _movieContext.SaveChangesAsync();
return movie;
}
GET Method
The HTTP GET request is used get the all deatils from data source. If we pass any paramater then the details will be fetched based on the parameter.
[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;
}
PUT Method
The HTTP PUT method is used to update an existing record in the data source in the RESTful architecture.
[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;
}
Delete Method
The HTTP DELETE request is used to delete an existing record in the data source in the RESTful architecture.
[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();
}
Once you are done with the code change we will go to Developer PowerShell or Command Prompt and execute the below command to build and run the application.
dotnet build
dotnet run
CRUD Operations
Now, go to Postman and Create New Http Request.
POST Method
http://localhost:<portnumber>/api/movies
GET Method
We can test the application by calling the two endpoints from Postman as follows:
http://localhost:{port}/api/movies
http://localhost:{port}/api/movies/{id}
PUT Method
We will update the existing movie by passing the movie id number which generated while adding the movie.
http://localhost:{port}/api/movies/{id}
DELETE Method
Execute the following command in Postman to test the Delete method.
http://localhost:{port}/api/movies/{id}
We can verify the data for every action in SQL Server management studio.
We will continue to create movie UI using react and consume the web API requests in the next section. You can find the full project in this GitHub Repo.
Thanks for reading!