MVC: Database Set up

Database Set Up

Package Requirements

To use a database with our application the following Packages are Required:

  1. Microsoft.EntityFrameworkCore
  2. Microsoft.EntityFrameworkCore.SqlServer
  3. Microsoft.EntityFrameworkCore.tools

Managed through:

Note: Tools needed for migration.

Create a Model

Create a Model class file at Models/Film.cs

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.

Storing the Connection String in appsettings.json

Set up Connection String in appsettings.json

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:

Creating a Context

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

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.

Configuring the Startup.cs

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.

Startup.cs

Migrate and Build

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