The user needs a boilerplate setup for a C# ASP.NET Core web API with Entity Framework. Given they didn't specify the version, I'll assume ASP.NET Core 8 and use a minimal hosting model. I can include a typical project structure featuring essential files like Program.cs, appsettings.json, a DbContext, an entity, a repository, and a controller. It sounds like they want a concise solution with minimal code but not just a skeleton. I'll include commands like dotnet new webapi too.Compiling a .NET 8 ASP.NET Core API
I need to ensure the code compiles for .NET 8 by using top-level statements in Program.cs and including using Microsoft.EntityFrameworkCore;. I'll add builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); and include necessary EF NuGet packages, leaning towards SQL Server for stability.
For creating the project, I'll suggest using the CLI command: dotnet new webapi -n SampleApi. My final response will include minimal code snippets and essential project files like .csproj, appsettings.json, Models, Data, and Controllers, along with optional migration commands. I'll keep it concise and avoid unnecessary explanations. Below is a minimal but complete boilerplate for an ASP.NET Core Web API with Entity Framework Core.
Assume .NET 8 and SQL Server. Adjust namespaces and project name as needed.
Adjust the connection string for your SQL Server instance.
3. DbContext (Data/AppDbContext.cs)
csharp
using Microsoft.EntityFrameworkCore;
using SampleApi.Models;
namespace SampleApi.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<TodoItem> TodoItems => Set<TodoItem>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<TodoItem>(entity =>
{
entity.HasKey(e => e.Id);
entity.Property(e => e.Title)
.IsRequired()
.HasMaxLength(200);
});
}
}
}
4. Entity model (Models/TodoItem.cs)
csharp
namespace SampleApi.Models
{
public class TodoItem
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public bool IsCompleted { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}
}