The context object allows querying and saving data. The database context is derived from Microsoft.EntityFrameworkCore.DbContext and specifies the entities to include in the data model.
Add a class called MvcMovieContext inside the Data folder of the project:
Replace the code inside MvcMovieContext with the below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MvcMovie.Models;
namespace MvcMovie.Data
{
public class MvcMovieContext : DbContext
{
public MvcMovieContext (DbContextOptions<MvcMovieContext> options)
: base(options)
{
}
public DbSet<MvcMovie.Models.Movie> Movie { get; set; }
}
}
Add the data context as a service in program.cs file
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<MvcMovieContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("MvcMovieContext")));
This will let us perform a Dependency Injection to inject the MvcMovieContext database context into any controller later. We will discuss dependency injection little later.
Add connection string
Let us add a connection string in appsettings.json file so that the application knows which database to connect to. In our case we will be using local DB which is a sequel server instance for developers. Local DB is installed automatically when we install Visual Studio.
Entity framework is capable of creating database and tables by what is called as migrations which we will look into later. To keep the demo simple, let us manually create the required database, table and the data using the query below:
use master;
go
create database MvcMovie;
go
use MvcMovie;
go
CREATE TABLE [dbo].[Movie] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Title] NVARCHAR (MAX) NULL,
[ReleaseDate] DATETIME2 (7) NOT NULL,
[Genre] NVARCHAR (MAX) NULL,
[Price] DECIMAL (18, 2) NOT NULL
);
insert into Movie values ('Titanic', '1/1/1997','Romance',99);
insert into Movie values ('Jurassic Park', '12/25/1993','Fiction',199);
Next, we will look into how to use the context object in the controller, instead of the fake context object that the application is currently using.