3. MVC Web App (Database-First) Flashcards

1
Q

How do you create a new database context class from an existing database?

A

By using the dotnet ef dbcontext scaffold command.

eg.
~~~
dotnet ef dbcontext scaffold “” Npgsql.EntityFrameworkCore.PostgreSQL -p
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What NuGet packages do you need for generating a db context class and entity classes from an existing database?

A
  1. Microsoft.EntityFrameworkCore.Tools
  2. Microsoft.EntityFrameworkCore.Tools.DotNet
  3. Microsoft.EntityFrameworkCore.Design
  4. Microsoft.EntityFrameworkCore.Relational.Design
  5. Microsoft.EntityFrameworkCore.SqlServer — or the equivalent for a different database provider
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you configure a .NET web app to use a certain DB context and connect to a given database in the Startup file?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you use a DB context in an MVC controller?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly