EF infers names for tables ect and their intent, here are some examples
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
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)
{
}
}
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
Register PizzaContext for DI
Specifiy we are using SQLite
Specify conntection string
Create a Migration
Generate a migration
detnet ef migrations add MigrationName --context PizzaContext
create a migration of name MigrationName
this will also create a directory called migratuions where all migrations will reside
Apply the migration
dotnet ef database update --context PizzaContext
you only need to specify context if there are multiple db contexts (databse connections)