aspnetcore/tutorials/first-mvc-app/working-with-sql/includes/working-with-sql8.md
:::moniker range="= aspnetcore-8.0"
This part of the tutorial series focuses on working with a SQL database in your ASP.NET Core MVC application.
You’ll learn how to:
This tutorial uses a database you set up in the previous step: xref:tutorials/first-mvc-app/adding-model.
The MvcMovieContext 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 Program.cs file:
The ASP.NET Core Configuration system reads the ConnectionString key. For local development, it gets the connection string from the appsettings.json file:
The ASP.NET Core Configuration system reads the ConnectionString. For local development, it gets the connection string from the appsettings.json file:
[!INCLUDE managed-identities]
LocalDB:
From the View menu, open SQL Server Object Explorer (SSOX).
Right-click on the Movie table (dbo.Movie) > View Designer
Note the key icon next to ID. By default, EF makes a property named ID the primary key.
Right-click on the Movie table > View Data
-->
Create a new class named SeedData in the Models folder. Replace the generated code with the following:
If there are any movies in the database, the seed initializer returns and no movies are added.
if (context.Movie.Any())
{
return; // DB has been seeded.
}
<a name="si"></a>
Replace the contents of Program.cs with the following code. The new code is highlighted.
Delete all the records in the database. You can do this with the delete links in the browser or from SSOX.
Test the app. Force the app to initialize, calling the code in the Program.cs file, so the seed method runs. To force initialization, close the command prompt window that Visual Studio opened, and restart by pressing Ctrl+F5.
Update Program.cs with the following highlighted code:
Delete all the records in the database.
Test the app. Stop it and restart it so the SeedData.Initialize method runs and seeds the database.
The app shows the seeded data.
[!div class="step-by-step"] Previous: Adding a model Next: Adding controller methods and views
:::moniker-end