Getting started & first migration

Install

# DB provider
dotnet add package Microsoft.EntityFrameworkCore.Sqlite

# Entity Framework Core tools
dotnet add package Microsoft.EntityFrameworkCore.Design

# EF CLI
dotnet tool install --global dotnet-ef

Add code

Creating a model

public class Pizza
{
		// This will be the PK (infered)
		// You can change this name using the [Key] attribute
    public int Id { get; set; } 

		// Will generate a FK
    public Sauce? Sauce { get; set; }
    
    // Topping table will have an FK pointing to Pizza
    public ICollection<Topping>? Toppings { get; set; }

		// You can also add annotations to specify additional features
		[Required]
    [MaxLength(100)]
    public string? Name { get; set; }
}

Create a DB Context

  1. Create a context Class, that inherits from DbContext
    This must also use the options I as shown below, this means that you can pass in config to the DbContext class via your class
public class PizzaContext : DbContext
{
    public PizzaContext (DbContextOptions<PizzaContext> options)
        : base(options)
    {
    }
}

  1. Now add DbSet objects, with type of your models
    They will create tables in your db corresponding to your models
public class PizzaContext : DbContext
{
    public PizzaContext (DbContextOptions<PizzaContext> options)
        : base(options)
    {
    }

    public DbSet<Pizza> Pizzas => Set<Pizza>(); // Pizzas will be the table name
    public DbSet<Topping> Toppings => Set<Topping>();
    public DbSet<Sauce> Sauces => Set<Sauce>();
}

Update Program.cs

builder.Services.AddSqlite<PizzaContext>("Data Source=pizza.db");
// Connection string should be stored securly, in this case are are doing it 
// locally

Create a Migration

Generate a migration

detnet ef migrations add MigrationName --context PizzaContext

Apply the migration

dotnet ef database update --context PizzaContext