Setting up EF Core
Setting up Entity Framework Core¶
Entity Framework Core (EF Core) is an essential part of the CacheCows tech stack, used for object-relational mapping in our CowPress and ToDoMoo applications. This guide details the steps to install and configure EF Core in your development environment.
Installation¶
EF Core is a lightweight, extensible, open-source, and cross-platform version of the popular Entity Framework data access technology.
-
Prerequisites
- Ensure you have the .NET SDK installed. EF Core requires .NET Standard 2.0 or later. -
Install EF Core
- In your project directory, use the .NET CLI to install the EF Core package.
- Rundotnet add package Microsoft.EntityFrameworkCore
. -
Install Database Provider
- EF Core supports various database providers. Install the one you need for your project. For example, for SQL Server, use:
- For other databases like PostgreSQL, MySQL, etc., find the corresponding NuGet package.
EF Core Tools¶
For performing database migrations and other EF Core-related tasks, installing the EF Core command-line tools is recommended.
-
Install EF Core CLI
- Run the following command:
- This installs the command-line tools globally on your machine. -
Verify Installation
- Verify the installation by runningdotnet ef
in the terminal.
Configuring EF Core in a Project¶
-
Create a Data Model
- Define your data model as classes in C#. Each class will correspond to a table in the database. -
Add a DbContext
- Create a subclass ofDbContext
representing a session with the database. It allows querying and saving data. -
Register DbContext
- In theStartup.cs
file (for ASP.NET Core projects), register your context with dependency injection in theConfigureServices
method:
-
Connection Strings
- Store your database connection strings securely, for example, inappsettings.json
or an environment variable. -
Create and Update Database
- Use migrations to create or update your database. Run:
With EF Core set up, you are now ready to work on database-related tasks in the CacheCows projects.
Created : November 16, 2023