Beginner database tutorial
EF Core maps C# classes to database tables. SQLite is a small file database that is ideal for learning and local prototypes.
1. Create and install packages
dotnet new web -n StudentEf
cd StudentEf
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Design2. Create the model and context
public class Student
{
public int Id { get; set; }
public string Name { get; set; } = "";
public string Course { get; set; } = "";
}
public class SchoolDb(DbContextOptions<SchoolDb> options) : DbContext(options)
{
public DbSet<Student> Students => Set<Student>();
}Save these classes in Student.cs and SchoolDb.cs.
3. Configure the database
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<SchoolDb>(options =>
options.UseSqlite("Data Source=school.db"));
var app = builder.Build();
app.MapGet("/students", async (SchoolDb db) =>
await db.Students.AsNoTracking().ToListAsync());
app.MapPost("/students", async (Student student, SchoolDb db) =>
{
db.Students.Add(student);
await db.SaveChangesAsync();
return Results.Created($"/students/{student.Id}", student);
});
app.Run();Add using Microsoft.EntityFrameworkCore; at the top. Registering DbContext lets ASP.NET Core inject it into each request.
4. Create the database
dotnet tool install --global dotnet-ef
dotnet ef migrations add InitialCreate
dotnet ef database update
dotnet runUse an HTTP client to POST {"name":"Asha","course":"C#"} to /students, then GET the collection.
Why migrations matter
A migration records a schema change as source-controlled code. The update command applies it to the SQLite file. Do not delete migrations to fix a production database; create a new migration.
Practice
Add a CreatedAt property, create a migration, and sort the GET query by name. Add validation so a blank name returns 400.
Self-check
DbContext represents a unit of work. DbSet represents a table-like collection. Async database calls keep the server responsive while I/O is running.
Return to the .NET Core learning path · Official EF Core SQLite guide
No comments:
Post a Comment
Please do not enter any spam link in the comment box.