Skip to content

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.

  1. Prerequisites
    - Ensure you have the .NET SDK installed. EF Core requires .NET Standard 2.0 or later.

  2. Install EF Core
    - In your project directory, use the .NET CLI to install the EF Core package.
    - Run dotnet add package Microsoft.EntityFrameworkCore.

  3. Install Database Provider
    - EF Core supports various database providers. Install the one you need for your project. For example, for SQL Server, use:

    dotnet add package Microsoft.EntityFrameworkCore.SqlServer
    

    - 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.

  1. Install EF Core CLI
    - Run the following command:

    dotnet tool install --global dotnet-ef
    

    - This installs the command-line tools globally on your machine.

  2. Verify Installation
    - Verify the installation by running dotnet ef in the terminal.

Configuring EF Core in a Project

  1. Create a Data Model
    - Define your data model as classes in C#. Each class will correspond to a table in the database.

  2. Add a DbContext
    - Create a subclass of DbContext representing a session with the database. It allows querying and saving data.

  3. Register DbContext
    - In the Startup.cs file (for ASP.NET Core projects), register your context with dependency injection in the ConfigureServices method:

    services.AddDbContext<YourDbContext>(options =>
       options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    

  4. Connection Strings
    - Store your database connection strings securely, for example, in appsettings.json or an environment variable.

  5. Create and Update Database
    - Use migrations to create or update your database. Run:

    dotnet ef migrations add InitialCreate
    dotnet ef database update
    

With EF Core set up, you are now ready to work on database-related tasks in the CacheCows projects.


Last update : November 17, 2023
Created : November 16, 2023