Before we begin, make sure you have the following prerequisites installed on your machine:
- .NET Core SDK (version 3.1 or higher)
- Visual Studio Code or Visual Studio (optional but recommended)
Let’s get started:
Step 1: Create a new .NET Core Web API project
Open a terminal or command prompt and run the following command to create a new .NET Core Web API project:
dotnet new webapi -o MyWebApi
Step 2: Install Entity Framework Core packages
Navigate to the project directory:
cd MyWebApi
Then, run the following command to install Entity Framework Core packages:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
Step 3: Define your data model
Open the Models
folder and create a new class file called TodoItem.cs
. Replace the existing code with the following:
using System.ComponentModel.DataAnnotations;
namespace MyWebApi.Models
{
public class TodoItem
{
[Key]
public int Id { get; set; }
[Required]
public string Title { get; set; }
public bool IsCompleted { get; set; }
}
}
Step 4: Configure your database connection
Open the appsettings.json
file and update the ConnectionStrings
section with your database connection details. For example:
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=MyDatabase;User Id=sa;Password=your_password;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Step 5: Create a DbContext class
Open the Models
folder and create a new class file called AppDbContext.cs
. Replace the existing code with the following:
using Microsoft.EntityFrameworkCore;
namespace MyWebApi.Models
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<TodoItem> TodoItems { get; set; }
}
}
Step 6: Configure the DbContext in Startup.cs
Open the Startup.cs
file and locate the ConfigureServices
method. Replace the existing code with the following:
using Microsoft.EntityFrameworkCore;
using MyWebApi.Models;
namespace MyWebApi
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
}
}
}
Step 7: Generate database migration
Open a terminal or command prompt and run the following command to generate the initial database migration:
dotnet ef migrations add InitialCreate
Step 8: Apply database migration
Run the following command to apply the migration and create the database:
dotnet ef database update
Step 9: Create a controller
Open the Controllers
folder and create a new class file called TodoItemsController.cs
. Replace the existing code with the following:
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyWebApi.Models;
namespace MyWebApi.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class TodoItemsController : ControllerBase
{
private readonly AppDbContext _context;
public TodoItemsController(AppDbContext context)
{
_context = context;
}
[HttpGet]
public ActionResult<IEnumerable<TodoItem>> GetTodoItems()
{
return _context.TodoItems.ToList();
}
[HttpGet("{id}")]
public ActionResult<TodoItem> GetTodoItem(int id)
{
var todoItem = _context.TodoItems.Find(id);
if (todoItem == null)
{
return NotFound();
}
return todoItem;
}
[HttpPost]
public ActionResult<TodoItem> CreateTodoItem(TodoItem todoItem)
{
_context.TodoItems.Add(todoItem);
_context.SaveChanges();
return CreatedAtAction(nameof(GetTodoItem), new { id = todoItem.Id }, todoItem);
}
[HttpPut("{id}")]
public IActionResult UpdateTodoItem(int id, TodoItem todoItem)
{
if (id != todoItem.Id)
{
return BadRequest();
}
_context.Entry(todoItem).State = EntityState.Modified;
_context.SaveChanges();
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult DeleteTodoItem(int id)
{
var todoItem = _context.TodoItems.Find(id);
if (todoItem == null)
{
return NotFound();
}
_context.TodoItems.Remove(todoItem);
_context.SaveChanges();
return NoContent();
}
}
}
Step 10: Run the application
Open a terminal or command prompt, navigate to the project directory (MyWebApi
), and run the following command to start the API:
dotnet run
Congratulations! You have created a Web API using .NET Core with the Code First approach. You can now use tools like Postman or cURL to interact with the API endpoints at https://localhost:5001/api/todoitems
.
Please note that this is a basic example and may not include all the necessary error handling, security measures, or best practices for a production-ready application.