Work with a database and ASP.NET Core

By Rick Anderson and Joe Audette

View or download sample code (how to download).

The RazorPagesMovieContext object handles the task of connecting to the database and mapping Movie objects to database records. The database context is registered with the Dependency Injection container in the ConfigureServices method in Startup.cs:

// This method gets called by the runtime. 
// Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is 
        // needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    services.AddDbContext<RazorPagesMovieContext>(options =>
      options.UseSqlServer(
          Configuration.GetConnectionString("RazorPagesMovieContext")));
}

For more information on the methods used in ConfigureServices, see:

The ASP.NET Core Configuration system reads the ConnectionString. For local development, it gets the connection string from the appsettings.json file.

The name value for the database (Database={Database name}) will be different for your generated code. The name value is arbitrary.

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "RazorPagesMovieContext": "Server=(localdb)\\mssqllocaldb;Database=RazorPagesMovieContext-1234;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

When the app is deployed to a test or production server, an environment variable can be used to set the connection string to a real database server. See Configuration for more information.

SQL Server Express LocalDB

LocalDB is a lightweight version of the SQL Server Express database engine that's targeted for program development. LocalDB starts on demand and runs in user mode, so there's no complex configuration. By default, LocalDB database creates *.mdf files in the C:/Users/<user/> directory.

  • From the View menu, open SQL Server Object Explorer (SSOX).

    View menu

  • Right click on the Movie table and select View Designer:

    Contextual menu open on Movie table

    Movie table open in Designer

Note the key icon next to ID. By default, EF creates a property named ID for the primary key.

  • Right click on the Movie table and select View Data:

    Movie table open showing table data

Seed the database

Create a new class named SeedData in the Models folder with the following code:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;

namespace RazorPagesMovie.Models
{
    public static class SeedData
    {
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new RazorPagesMovieContext(
                serviceProvider.GetRequiredService<
                    DbContextOptions<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 there are any movies in the DB, the seed initializer returns and no movies are added.

if (context.Movie.Any())
{
    return;   // DB has been seeded.
}

Add the seed initializer

In Program.cs, modify the Main method to do the following:

  • Get a DB context instance from the dependency injection container.
  • Call the seed method, passing to it the context.
  • Dispose the context when the seed method completes.

The following code shows the updated Program.cs file.

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using RazorPagesMovie.Models;
using System;
using Microsoft.EntityFrameworkCore;

namespace RazorPagesMovie
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    var context=services.
                        GetRequiredService<RazorPagesMovieContext>();
                    context.Database.Migrate();
                    SeedData.Initialize(services);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }
            }

            host.Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

A production app would not call Database.Migrate. It's added to the preceding code to prevent the following exception when Update-Database has not been run:

SqlException: Cannot open database "RazorPagesMovieContext-21" requested by the login. The login failed. Login failed for user 'user name'.

Test the app

  • Delete all the records in the DB. You can do this with the delete links in the browser or from SSOX

  • Force the app to initialize (call the methods in the Startup class) so the seed method runs. To force initialization, IIS Express must be stopped and restarted. You can do this with any of the following approaches:

    • Right click the IIS Express system tray icon in the notification area and tap Exit or Stop Site:

      IIS Express system tray icon

      Contextual menu

      • If you were running VS in non-debug mode, press F5 to run in debug mode.
      • If you were running VS in debug mode, stop the debugger and press F5.

The app shows the seeded data:

Movie application open in Chrome showing movie data

The next tutorial will clean up the presentation of the data.