2. Console App (Code-First) Flashcards
What’s the role of the DbContext
class in EF?
It practically represents a database.
To connect to a database, we write a class that derives from DbContext
. Each DbContext
class we write gives us access to a specific database.
What’s a DbSet
in the context of EF?
Practically, a table in the database.
In DbContext, we can create properties that are type DbSet. The generic type parameter T will be an entity.
How do you specify a connection string for a DbContext class?
By overriding OnConfiguring, which takes in a DbContextOptionsBuilder parameter that we can use to set the connection string to our DB.
What NuGet package do you need to work with a PostgreSQL database on EF Core?
npsql.EntityFrameworkCore.PostgreSQL
What NuGet package do you need to use EF Core tools?
Microsoft.EntityFrameworkCore.Tools
How do you add migrations to a project using EF Core?
By running dotnet ef migrations add -p
.
How do you apply migrations to a database using EF Core?
By running dotnet ef database update -p
.
How do you create a database using EF Core code-first approach?
By creating a new class that derives from DbContext
, configuring it by overriding the OnConfiguring
base method which takes in a DbContextOptionsBuilder
object for dependency injection, and then creating and running migrations.
How do you create a table using EF Core code-first approach?
By creating a new class to be used as an entity, defining properties in it to be mapped to columns, and adding a new property to your DbContext
child class with the type DbSet
— T being the entity class type.
How do you access a database table in code?
By instantiating a context class object and calling the DbSet property that corresponds to the table you’d like to access.
eg.
var db = MyContexT(); var tb = db.MyTable; ~~~ ~~~
How do you add a new record to the database in code?
By using a context object to access the table and call the Add method on it.
eg.
var db = MyContexT(); db.MyTable.Add(new MyRecord {Name = "Foo"}); ~~~ ~~~
After using a context object to write data to a database, what else must you do in order for those writes to actually be applied?
Use the context object to save changes.
eg. db.SaveChanges();