Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
By Joe Audette
The RazorPagesMovieContext object handles the task of connecting to the database and mapping Movie objects to database records. Register the database context with the dependency injection container in Program.cs:
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("RazorPagesMovieContext") ?? throw new InvalidOperationException("Connection string 'RazorPagesMovieContext' not found.");
builder.Services.AddDbContext<RazorPagesMovieContext>(options => options.UseSqlServer(connectionString));
// Add services to the container.
builder.Services.AddRazorPages();
The ASP.NET Core Configuration system reads the ConnectionString key. For local development, the configuration gets the connection string from the appsettings.json file.
The generated connection string is similar to the following JSON:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"RazorPagesMovieContext": "Server=(localdb)\\mssqllocaldb;Database=RazorPagesMovieContext-f2e0482c-952d-4b1c-afe9-a1a3dfe52e55;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
Warning
This article uses a local database that doesn't require the user to be authenticated. Production apps should use the most secure authentication flow available. For more information on authentication for deployed test and production apps, see Secure authentication flows.
SQL Server Express LocalDB
LocalDB is a lightweight version of the SQL Server Express database engine that's designed for program development. LocalDB starts on demand and runs in user mode, so there's no complex configuration. By default, LocalDB creates *.mdf database files in the C:\Users\<user>\ directory.
From the View menu, open SQL Server Object Explorer (SSOX).
Right-click on the
Movietable and select View Designer:
Note the key icon next to
ID. By default, EF creates a property namedIDfor the primary key.Right-click on the
Movietable and select View Data:
Seed the database
Create a new class named SeedData in the Models folder with the following code:
using Microsoft.EntityFrameworkCore;
namespace RazorPagesMovie.Models;
public static class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new RazorPagesMovieContext(
serviceProvider.GetRequiredService<
DbContextOptions<RazorPagesMovieContext>>()))
{
if (context == null || context.Movie == null)
{
throw new ArgumentNullException("Null RazorPagesMovieContext");
}
// Look for any movies.
if (context.Movie.Any())
{
return; // DB has been seeded
}
context.Movie.AddRange(
new Movie
{
Title = "When Harry Met Sally",
ReleaseDate = DateTime.Parse("1989-2-12"),
Genre = "Romantic Comedy",
Price = 7.99M
},
new Movie
{
Title = "Ghostbusters ",
ReleaseDate = DateTime.Parse("1984-3-13"),
Genre = "Comedy",
Price = 8.99M
},
new Movie
{
Title = "Ghostbusters 2",
ReleaseDate = DateTime.Parse("1986-2-23"),
Genre = "Comedy",
Price = 9.99M
},
new Movie
{
Title = "Rio Bravo",
ReleaseDate = DateTime.Parse("1959-4-15"),
Genre = "Western",
Price = 3.99M
}
);
context.SaveChanges();
}
}
}
If the database contains any movies, the seed initializer returns and doesn't add any movies.
if (context.Movie.Any())
{
return;
}
Add the seed initializer
Update Program.cs with the following highlighted code:
using Microsoft.EntityFrameworkCore;
using RazorPagesMovie.Models;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("RazorPagesMovieContext") ?? throw new InvalidOperationException("Connection string 'RazorPagesMovieContext' not found.");
builder.Services.AddDbContext<RazorPagesMovieContext>(options => options.UseSqlServer(connectionString));
// Add services to the container.
builder.Services.AddRazorPages();
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
SeedData.Initialize(services);
}
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.MapStaticAssets();
app.MapRazorPages()
.WithStaticAssets();
app.Run();
In the preceding code, you modify Program.cs to do the following steps:
- Create a service scope with
app.Services.CreateScope(). - Obtain the service provider (IServiceProvider) from the scope.
- Call the
SeedData.Initializemethod, passing the service provider. - Dispose the service scope when the seed method completes. The
usingstatement ensures the scope is disposed.
The following exception occurs when you don't run Update-Database:
SqlException: Cannot open database "RazorPagesMovieContext-" requested by the login. The login failed.Login failed for user 'user name'.
Test the app
Delete all the records in the database so the seed method runs. Stop and start the app to seed the database. If the database isn't seeded, put a breakpoint on if (context.Movie.Any()) and step through the code.
The app shows the seeded data:
Next steps
ASP.NET Core