.NET REST API Flashcards
What is the Microsoft Framework used for relational database interaction?
Entity Framework Core
What are the CLI commands used for building a .Net Rest Api
dotnet new sln
dotnet new webapi -o [projname]
dotnet new classlib -f [framework] -o [name]
dotnet sln add [path]
What CLI command is used to add references to neighbouring class libraries?
dotnet add app/app.csproj reference lib/lib.csproj
What are the main classlibs (aside from the main webapi) required for a rest api?
data -> for database interaction
services -> expressive methods for webapi use
test -> for testing
Class libs are a great way to seperate concerns and keep a clean working directory.
Which class defines the configuration & services for the REST API?
Startup.cs
Which NuGet packages are required to be added
Add the Microsoft.EntityFrameworkCore & the Microsoft.EntityFrameworkCore.Design. Also the NewtonSoft.Json package is useful.
How do you define a data Model
Create a class (in the data classlib /Models/) that contains the layout of each table in your DB, with each table being defined as a field. Each field that is another class requires another model.
What is a database context
A database context defines the context, or overall shape, of the database. It is a class that inherits from DbContext (EF CORE) and should have the following shapes
public GoodbooksDbContext() { } public GoodbooksDbContext(DbContextOptions options) : base(options) { } public virtual DbSet PluralOfModelName { get; set; }
How do you inject the EF CORE DbContext into the services.
In the ConfigureServices Method in Startup.cs:
services.AddDbContext(opts => {
opts.EnableDetailedErrors();
// setup database preference e.g. Postgres
});
How do you setup a service
Define an interface with the methods required (i.e. what you want to do with the database), and then implement that interface
How do you inject the EF Core database context into a service?
Create a readonly field, define an instance in the constructor parameters, then in the body assign the parameter to the readonly field.
private readonly GoodbooksDbContext _db; public BookService(GoodbooksDbContext db) { _db = db; }
What are the standard EF Core database Methods for CRUD operations
Create -> _db.Add()
Read -> _db.Find() / _db.ToList()
Update -> _db.Update()
Delete -> _db.Delete()
What EF Core method must be invoked on any non-read CRUD operation
_db.SaveChanges()
Where should the service be injected?
Into any controller class that uses it/ handles any http request. Inject using the interface of the service.
Where are the controllers located?
In the main web API project. They handle requests that come in.