2.0 KiB
Working with SQLite in an ASP.NET Core MVC project
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 ConfigureServices
method in the Startup.cs file:
[!code-csharpMain]
SQLite
The SQLite website states:
SQLite is a self-contained, high-reliability, embedded, full-featured, public-domain, SQL database engine. SQLite is the most used database engine in the world.
There are many third party tools you can download to manage and view a SQLite database. The image below is from DB Browser for SQLite. If you have a favorite SQLite tool, leave a comment on what you like about it.
Seed the database
Create a new class named SeedData
in the Models folder. Replace the generated code with the following:
[!code-csharpMain]
If there are any movies in the DB, the seed initializer returns.
if (context.Movie.Any())
{
return; // DB has been seeded.
}
Add the seed initializer
Add the seed initializer to the Main
method in the Program.cs file:
[!code-csharpMain]
Test the app
Delete all the records in the DB (So the seed method will run). Stop and start the app to seed the database.
The app shows the seeded data.