Sub topic 2
Setting Up a Project with EF Core and SQLite
Before you can use EF Core, you need a project with the right pieces installed. This chapter walks you through that setup, one step at a time.
What You Will Install
EF Core comes in parts. You add only the parts your project needs.
- A package is a library of ready-made code that you add to a project. .NET packages come from an online store called NuGet.
- A database provider is a package that lets EF Core talk to one kind of database. Each database, such as SQL Server, PostgreSQL, or SQLite, has its own provider.
- SQLite is a small database that keeps all its data in a single file. It needs no server, so it works well for learning.
- A tool is a command-line program. The
dotnet-eftool runs EF Core commands from your terminal.
| Item | What it does |
|---|---|
| Microsoft.EntityFrameworkCore.Sqlite | Gives you the SQLite provider, and installs EF Core itself along with it |
| Microsoft.EntityFrameworkCore.Design | Lets the dotnet-ef tool read your project's code |
| dotnet-ef | Creates and applies migrations from the terminal |
Worked Example: Create the Project
Open a terminal and run these commands:
dotnet new console -o EfCoreDemo
cd EfCoreDemo
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet tool install --global dotnet-efHere is what each line does:
dotnet new console -o EfCoreDemomakes a new console app in a folder namedEfCoreDemo.cd EfCoreDemomoves you into that folder.- The first
dotnet add packageline adds the SQLite provider, and EF Core comes with it. - The second
dotnet add packageline adds the design-time package, which the tool needs. dotnet tool install --global dotnet-efinstalls the tool for every project on your computer. "Global" means you only have to do this once.
Check Your Setup
Make sure the tool works:
dotnet ef --versionYou should see a version number. Next, open EfCoreDemo.csproj. It should now list both packages under PackageReference entries. Finally, build the project:
dotnet buildIf the build succeeds, the setup is done.
Exercises
Exercise
Why does this project use SQLite while you are learning?
Show answer
SQLite stores the whole database in one file and needs no separate server, so you have nothing extra to install or run.
Exercise
Which package does the dotnet-ef tool need inside your project, and what happens if you leave it out?
Show answer
It needs Microsoft.EntityFrameworkCore.Design. Without it, commands such as dotnet ef migrations add fail because the tool cannot read your project's code.
Exercise
You install dotnet-ef in one project. Do you have to install it again for your next project?
Show answer
No. The --global option installs it for your whole user account, so every project can use it.