3. MVC Web App (Database-First) Flashcards
How do you create a new database context class from an existing database?
By using the dotnet ef dbcontext scaffold
command.
eg.
~~~
dotnet ef dbcontext scaffold “” Npgsql.EntityFrameworkCore.PostgreSQL -p
~~~
What NuGet packages do you need for generating a db context class and entity classes from an existing database?
- Microsoft.EntityFrameworkCore.Tools
- Microsoft.EntityFrameworkCore.Tools.DotNet
- Microsoft.EntityFrameworkCore.Design
- Microsoft.EntityFrameworkCore.Relational.Design
- Microsoft.EntityFrameworkCore.SqlServer — or the equivalent for a different database provider
How do you configure a .NET web app to use a certain DB context and connect to a given database in the Startup file?
In the ConfigureServices
method, you use the AddDbContext
method of the IServiceCollection
parameter with the type parameter of the DB context class you’d like to use, and then using a predicate to declare the DB provider and the connection string you’d like to use.
eg.
services.AddDbContext(
options => options.UseSqlServer(connStr));
~~~
```
PS. In order for this to work, you must have a constructor in your DB context class that takes in a DbContextOptions
parameter and passes it to its base class using the base
keyword.
eg.
public SomeContext(DbContextOptions options)
: base(options)
{
}
~~~
~~~
How do you use a DB context in an MVC controller?
You define a constructor for the controller that takes in an instance of the given context and stores it in a property and the ASP.NET dependency injection will take care of passing an instance into this constructor automatically.