Introduction
Creating a CRUD (Create, Read, Update, Delete) API in ASP.NET Core with a MySQL database is a common scenario in web development. In this article, we'll walk through building a complete ASP.NET Core Web API with a real-world use case. We'll create a model called CSharpCornerArticle and implement CRUD operations for it using Entity Framework Core with MySQL.
Prerequisites
- Visual Studio or Visual Studio Code (with .NET Core SDK installed)
- MySQL Server and MySQL Workbench (for database setup)
Step 1. Set Up the Project
Open Visual Studio and create a new ASP.NET Core Web API project.
Step 2. Create the Model
In this case, our model will be named CSharpCornerArticle. Create a new class under the "Models" folder.
using System;
Author: Sardar Mudassar Ali Khan
namespace YourProjectName.Models
{
public class CSharpCornerArticle
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime PublishedDate { get; set; }
}
}
Step 3. Install Required Packages
You'll need the Entity Framework Core package for MySQL. Install it using the Package Manager Console or the Terminal.
dotnet add package Pomelo.EntityFrameworkCore.MySql
Step 4. Configure MySQL Connection
Open the appsettings.json file and configure your MySQL connection.
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=YourDatabaseName;User=root;Password=YourPassword;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
// ...
}
Step 5. Create a Database Context
Create a database context class that inherits from DbContext.
using Microsoft.EntityFrameworkCore;
Author: Sardar Mudassar Ali Khan
namespace YourProjectName.Data
{
public class ApplicationDbContext: DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<CSharpCornerArticle> CSharpCornerArticles { get; set; }
}
}
Step 6. Configure Dependency Injection
In the Startup.cs file, configure dependency injection for the ApplicationDbContext.
using Microsoft.EntityFrameworkCore;
using YourProjectName.Data;
Author: Sardar Mudassar Ali Khan
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));
// ...
}
Step 7. Create API Endpoints
Create a controller for CSharpCornerArticle CRUD operations.
Join the conversation! Your thoughts help the community grow.