To use a database with our application the following Packages are Required:
Managed through:
Note: Tools needed for migration.
Create a Model class file at Models/Film.cs
Tip: The [Key] attribute tells the Model the Id is a primary key. The [Required] attribute tells the Model that the FilmTitle is a required field. Validation on this can then be done server and/or client side.
Set up Connection String in appsettings.json
The above shows the connection string for a MSSQL database. You can connect to a range for different databases, for example to connect to a SQLite database the connection string may appear:
As we're using Entity Framework to manage our database we need to establish a context which is achieved via the DbContext class.
Part of the Entity Framework Core, the DbContext class represents a session with a database and provides an API for working with the database.
To establish a Context, create a class file at Models/ApplicationDbContext.cs
This was named ApplicationDbContext as it will be the main DbContext for our application. As that implies you can establish more than one DbContext to allow any given application to connect to multiple datasources.
Once created, we need to make the Context knownn to the application and this is done in the Startup.cs files ConfigureServices() method by adding the Context in as a service.
Use the console to run the migration command and then update the database
Add-Migration Initial
Update-Database
It is important to run both console commands. The Add-Migration command can be given a name by the developer. It this example, it was sensible to call it Initial.
Tip: if using a MAC the terminal commands dither slightly use:
####### MAC VERSION ########
dotnet ef migrations add Initial --context ApplicationDbContext
dotnet ef database update --context ApplicationDbContext