Hello! In this tutorial we will build your own ASP.NET service with database and learn what is EF Core!
Requirements
- IDE like Visual Studio/JetBrains Rider
- .NET >= 10
- Base C# skill
- CPU (manually)
What is Entity Framework
EF Core is a tool for .NET developers that lets you work with databases using standard C# code without writing raw SQL queries. It automatically maps database tables into familiar C# classes and objects, handling all the heavy lifting behind the scenes. To fetch, modify, or save data, you simply write a few lines of C#, and EF Core translates them into the correct SQL commands. This speeds up development and protects you from typos and errors when interacting with a database.
Creating entity
First we need to create entity, is that object that will saving in database like postgres, sqlite, mssql, or oracle.
Create file with name MyData and paste this code
namespace ExampleProject;
public class MyData
{
public Guid Id { get; set; }
public required string Name { get; set; }
public required int Age { get; set; }
}
In this entity we have - Own Id, Name, Age
Creating DbContext
For work with EFC we need DbContext.
First we need to add EFC library -
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
using Microsoft.EntityFrameworkCore;
namespace ExampleProject;
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<MyData> MyData => Set<MyData>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<MyData>().Property(x => x.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<MyData>().HasKey(x => x.Id);
modelBuilder.Entity<MyData>().Property(x => x.Name).IsRequired();
modelBuilder.Entity<MyData>().Property(x => x.Age).IsRequired();
base.OnModelCreating(modelBuilder);
}
}
this code contains configuration for DB
Adding to DI
using ExampleProject;
using Microsoft.EntityFrameworkCore;
using Scalar.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();
builder.Services.AddControllers();
builder.Services.AddScoped<IMyService, MyService>();
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlite("Data Source=app.db"));
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.MapScalarApiReference();
}
app.MapControllers();
app.Run();
Updating our service
namespace ExampleProject;
public interface IMyService
{
Task<string> GetHello(string name);
}
public class MyService(AppDbContext db) : IMyService
{
public async Task<string> GetHello(string name)
{
await Task.Delay(150);
await db.MyData.AddAsync(new MyData { Name = name, Age = 25 });
await db.SaveChangesAsync();
return $"Hello, {name}!";
}
}
Top comments (0)