Comprehending the Requirements
I'm now zeroing in on the core of the matter. The user's need for a robust C# ASP.NET Core Web API boilerplate with EF Core is crystal clear. To that end, I'm focusing on key components that extend beyond the mere Program.cs file. The aim is to create something truly useful.
Mapping Out The Structure
The project structure is starting to crystallize. I'm prioritizing logical separation of concerns. Based on my understanding, a clear division into Models, DTOs, Controllers, and Services, all managed with Dependency Injection in Program.cs, is crucial. The configuration, especially the database connection string via appsettings.json, is also on my mind.
Formulating the Implementation
Now I'm digging deeper into the implementation details. I'm focusing on the essential CLI commands and the required NuGet packages, which are key for initializing the project. I'm also planning the folder structure and how to include a Product entity. The CRUD operations and the DbContext setup are the current focus. I'm also considering the benefits and potential trade-offs of using a service layer.
Structuring the Output
I'm now focusing on formatting the output, ensuring clarity and ease of use. I'm leaning towards providing a file-by-file breakdown with Markdown code blocks. Instructions for migrations, often overlooked, are a must. I aim to guide the user through the process, from initial project creation via CLI to launching and using the API. I'm also carefully considering comments and notes about design patterns for further evolution.
Detailing the Implementation
Now I'm delving into the granular specifics. I'm focusing on the Product entity definition, the DbContext, and how they should interact within the overall structure. Also, I'm carefully considering how to handle the connection string and register the DbContext in Program.cs. I'm leaning toward including the Swagger setup as well, to make it ready to run without extra changes.
This is a complete, modern boilerplate for ASP.NET Core 8.0 Web API using Entity Framework Core (SQL Server).
It follows current best practices, including specific Clean Architecture folder structures, Async/Await patterns, and Dependency Injection.
Phase 1: Project Setup
Run these commands in your terminal to create the project and install necessary dependencies.
# 1. Create a new Web API project
dotnet new webapi -n MyApiProject
cd MyApiProject
# 2. Add Entity Framework Core packages
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Phase 2: The Code
Here is the file structure and code content.
1. Define the Model
File: Models/Product.cs
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace MyApiProject.Models
{
public class Product
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(100)]
public string Name { get; set; } = string.Empty;
[Column(TypeName = "decimal(18,2)")]
public decimal Price { get; set; }
public bool IsAvailable { get; set; } = true;
}
}
2. Database Context
File: Data/AppDbContext.cs
using Microsoft.EntityFrameworkCore;
using MyApiProject.Models;
namespace MyApiProject.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<Product> Products { get; set; }
}
}
3. Configuration (Connection String)
File: appsettings.json
Update the ConnectionStrings section.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyApiDb;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
4. Register Services (Dependency Injection)
File: Program.cs
using Microsoft.EntityFrameworkCore;
using MyApiProject.Data;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// 1. Register Entity Framework Context
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddControllers();
// 2. Add Swagger/OpenAPI
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
5. The Controller (API Endpoints)
File: Controllers/ProductsController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyApiProject.Data;
using MyApiProject.Models;
namespace MyApiProject.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly AppDbContext _context;
public ProductsController(AppDbContext context)
{
_context = context;
}
// GET: api/Products
[HttpGet]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
return await _context.Products.ToListAsync();
}
// GET: api/Products/5
[HttpGet("{id}")]
public async Task<ActionResult<Product>> GetProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
return product;
}
// POST: api/Products
[HttpPost]
public async Task<ActionResult<Product>> PostProduct(Product product)
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
// PUT: api/Products/5
[HttpPut("{id}")]
public async Task<IActionResult> PutProduct(int id, Product product)
{
if (id != product.Id)
{
return BadRequest();
}
_context.Entry(product).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// DELETE: api/Products/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
_context.Products.Remove(product);
await _context.SaveChangesAsync();
return NoContent();
}
private bool ProductExists(int id)
{
return _context.Products.Any(e => e.Id == id);
}
}
}
Phase 3: Run Migrations & Start
Now that the code is in place, you need to create the actual database based on your Model.
-
Create the Migration:
dotnet ef migrations add InitialCreate
-
Update the Database:
dotnet ef database update
-
Run the Application:
dotnet run
How to Test
Once the application is running (usually at https://localhost:xxxx), navigate to the Swagger UI in your browser:
https://localhost:YOUR_PORT/swagger
You will see an interactive interface to test your GET, POST, PUT, and DELETE endpoints immediately.