---
title: Use Scaleway Managed Redis™ for MySQL caching with Entity Framework
description: In this tutorial, you will learn to use Scaleway Redis™ as a record cache for Scaleway MySQL
tags: mysql redis entity-framework cache
products:
  - redis
dates:
  validation: 2025-07-16
  posted: 2023-11-25
  validation_frequency: 12
difficulty: beginner
usecase:
  - application-hosting
ecosystem:
  - third-party
---
import image from './assets/scaleway-mysql-db-information.webp'
import image2 from './assets/scaleway-mysql-user-information.webp'
import image3 from './assets/scaleway-redis-db-information.webp'

import Requirements from '@macros/iam/requirements.mdx'


This tutorial demonstrates the integration of a [Scaleway Redis™](https://www.scaleway.com/en/managed-database-for-redistm/) Instance as a record cache (commonly referred to as a second-level cache) for an application using a [Scaleway MySQL](https://www.scaleway.com/fr/managed-postgresql-mysql/) Instance through [Entity Framework](https://learn.microsoft.com/en-us/ef/).

<Message type="note">
    While the principles discussed apply to various technologies and data stores, the examples and demonstrations on this page specifically use MySQL as the database, Redis as the cache, and Entity Framework for .NET as the Object-Relational Mapping (ORM) tool.
</Message>

<Requirements />

- A Scaleway account logged into the [console](https://console.scaleway.com)
- [Owner](/iam/concepts/#owner) status or [IAM permissions](/iam/concepts/#permission) allowing you to perform actions in the intended Organization
- A [Redis™ Database Instance](/managed-databases-for-redis/how-to/create-a-database-for-redis/)
- A [MySQL Database Instance](/managed-databases-for-postgresql-and-mysql/how-to/create-a-database/)
- Installed the [.NET 7 SDK](https://dotnet.microsoft.com/en-us/download/dotnet/7.0)

## Scaffold a project with Entity Framework

Entity Framework acts as an object-relational mapper for databases, also providing the capability to cache data retrieved from the underlying data store and effectively reducing database-access costs.

The framework includes an integrated first-level cache that stores data for the scope of a single database session. Additionally, this tutorial explores a second-level cache, which functions as a globally shared record cache throughout the application to store recently accessed data.

To initiate a new .NET project, follow these steps using the dotnet CLI:

1. Create an empty project:
    ```
    dotnet new web -n ScalewayTutorial
    ```
2. Navigate to your newly created project folder and install dependencies for the data stores:
    - `Pomelo.EntityFrameworkCore.MySql` is the database driver for MySQL in Entity Framework.
    - `EFCoreSecondLevelCacheInterceptor` is the second-level cache extension for Entity Framework.
    - `EasyCaching.Redis` is a Redis™ driver for .NET.
    - `EasyCaching.Serialization.MessagePack`: provides serialization support for EasyCaching.

    ```
    dotnet add package Pomelo.EntityFrameworkCore.MySql
    dotnet add package EFCoreSecondLevelCacheInterceptor
    dotnet add package EasyCaching.Redis
    dotnet add package EasyCaching.Serialization.MessagePack
    ```

### Create a database schema

Begin by creating a database schema. For this tutorial, you can use the default `Program.cs` file to define your configuration.

Create a new class to represent a table:

```csharp
public class ProductModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}
```

### Set up the database context

To establish a connection between Entity Framework and your table model, create the following class representing the database context:

```csharp
public class ProductDatabase : DbContext
{
    public ProductDatabase(DbContextOptions<ProductDatabase> options)
        : base(options)
    { }
    public DbSet<ProductModel> Products => Set<ProductModel>();
}
```

These components define both the structure of your database schema and how Entity Framework interacts with it through the specified `ProductModel` class.

## Configure the MySQL database

Follow these steps to configure your MySQL database with Entity Framework:

1. Get the public IP and port of your Database Instance. You can locate this information on the **Database Instance Information** page of your Instance in the [Scaleway console](https://console.scaleway.com/rdb/instances), under **Public endpoint**.
    <Lightbox image={image} size="small" alt="Database Instance Information page in the Scaleway Console" />

2. Create a new user for your database, granting administrative rights from the **Users page**. Alternatively, use the default user.
    <Lightbox image={image2} size="small" alt="User page in the Scaleway Console" />

3. Generate a connection string for your database using the provided information:
    ```
    server=<IP address>;port=<Port>;user id=<Username>;password=<Password>;database=products
    ```

4. During the application startup, establish the connection between Entity Framework and your Scaleway MySQL Instance. Begin by clearing the content of `Program.cs`, then insert the following snippet:
    ```csharp
    var builder = WebApplication.CreateBuilder(args);

    builder.Services.AddDbContext<ProductDatabase>(
        (sp, options) =>
        var connectionString = "<your connection string>";
        {
            options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString))
                .AddInterceptors(sp.GetRequiredService<SecondLevelCacheInterceptor>());
        }
    );
    ```

    <Message type="important">
        Replace the connection string placeholder with the one from the previous step in that snippet.
    </Message>

## Configure the Redis™ cache

Follow these steps to configure your Redis™ cache with Entity Framework:

1. Get the public IP, port, and username for your Redis™ Instance. Locate this information on the **Database Instance Information** page of your Instance in the [Scaleway console](https://console.scaleway.com/redis/clusters), under **Public endpoints**.
<Lightbox image={image3} size="small" alt="Redis Overview page in the Scaleway Console" />

2. Download the TLS certificate using the <Icon name="toggle" /> button and store it in your project folder.

3. Generate a connection string using the provided information:
    ```
    <IP address>:<Port>,user=<Username>,password=<Password>,ssl=True
    ```

4. During application startup, configure the EasyCaching library to connect to your Redis™ Database Instance, and configure it as the second-level cache for Entity Framework. Insert this snippet at the end of `Program.cs`:
    ```csharp
    builder.Services.AddEasyCaching(options =>
    {
        options.WithMessagePack("redis-messagepack");
        options.UseRedis(config =>
        {
            config.SerializerName = "redis-messagepack";
            config.DBConfig.ConfigurationOptions = ConfigurationOptions.Parse("<your connection string>");
            var scalewayCert = new X509Certificate2("<your TLS certificate filename>", "");
            config.DBConfig.ConfigurationOptions.CertificateValidation +=
                (_, _, chain, _) => chain.ChainElements.Any(x => x.Certificate.Thumbprint == scalewayCert.Thumbprint);
        }, "scaleway-redis");
    });

    builder.Services.AddEFSecondLevelCache(options => options.UseEasyCachingCoreProvider("scaleway-redis"));
    ```

    <Message type="important">
        - Replace the connection string placeholder with the one generated in the previous step.
        - Replace the TLS certificate file name.
    </Message>

## Create the app

Your application is now fully configured to use the Redis™ Database Instance as a second-level cache for the Scaleway MySQL Instance. To test the setup, create a couple of API endpoints.

1. Define endpoints to interact with your Product database model for listing, retrieving, and adding `ProductModel`s. Add the following snippet at the end of Program.cs:
    ```csharp
    var app = builder.Build();

    app.MapGet("/product", (ProductDatabase db) => db.Products.Cacheable().ToList());

    app.MapPost("/product", (ProductModel p, ProductDatabase db) =>
    {
        db.Products.Add(p);
        db.SaveChanges();
    });

    app.MapGet("/product/{id}", (int id, ProductDatabase db) =>
    {
        return db.Products.Cacheable().FirstOrDefault(p => p.Id == id);
    });
    ```

    <Message type="note">
        Use `.Cacheable()` on Entity Framework queries to leverage the Redis™ second-level cache:
            - During a query, Entity Framework checks the cache for recent executions and retrieves results if available. Otherwise, it executes the query using the database and stores the result in the cache.
            - Any DML operation invalidates the cache on the related rows.
        To further configure the second-level cache behavior, refer to the [package extension documentation](https://github.com/VahidN/EFCoreSecondLevelCacheInterceptor).
    </Message>

2. Scaffold the database at launch. Insert the following snippet at the end of `Program.cs`:
    ```csharp
    using (var serviceScope = app.Services.CreateScope())
    {
        var context = serviceScope.ServiceProvider.GetRequiredService<ProductDatabase>();
        context.Database.Migrate();
    }

    app.Run();
    ```

3. Start the application. In your project folder, execute the following commands:
    ```
    dotnet build
    dotnet run
    ```
    The last command will display the local URL to access the web application and test your API endpoints.