title | author | description | ms.author | ms.date | monikerRange | uid | ms.custom |
---|---|---|---|---|---|---|---|
Part 5, work with a database in an ASP.NET Core MVC app |
wadepickett |
Part 5 of tutorial series on ASP.NET Core MVC. |
wpickett |
04/23/2024 |
>= aspnetcore-3.1 |
tutorials/first-mvc-app/working-with-sql |
engagement-fy23 |
By Rick Anderson and Jon P Smith.
:::moniker range=">= aspnetcore-8.0"
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:
When the app is deployed to a test or production server, an environment variable can be used to set the connection string to a production SQL Server. For more information, see Configuration.
LocalDB:
- Is a lightweight version of the SQL Server Express Database Engine, installed by default with Visual Studio.
- Starts on demand by using a connection string.
- Is targeted for program development. It runs in user mode, so there's no complex configuration.
- By default creates .mdf files in the C:/Users/{user} directory.
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.
}
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