'Store Entity Framework Core SQLite file in project-relative subdirectory

I have an ASP.NET Core 2.0 app using Entity Framework Core and the SQLite Provider. I am trying to store the SQLite database file in a subdirectory (specifically data\database\sqlite.db) however if I set the Connection String to Data Source=data\database\sqlite.db I get the following exception as soon as I run dbContext.Database.Migrate():

Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 14: 'unable to open database file'.

If I set it to Data Source=sqlite.db it works as expected without throwing exceptions (but not in the directory I need it to be stored in). What do I need to do to store the SQLite database file in a sub-directory relative to the current working directory?

For the sake of context: I need the SQLite database file stored in a sub-directory because this app is running in a Docker Container, this specific directory is mapped to a Docker volume so the database persists when the container is replaced.



Solution 1:[1]

I had a similar problem. I suppose that you are running your app in a .NET Core environment. You can do this in your "DbContext" class:

internal class YourDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        string baseDir = AppDomain.CurrentDomain.BaseDirectory;

        //if "bin" is present, remove all the path starting from "bin" word
        if (baseDir.Contains("bin"))
        {
            int index = baseDir.IndexOf("bin");
            baseDir = baseDir.Substring(0, index);
        }

        //String interpolation to reach the right path
        options.UseSqlite($"Data Source={baseDir}YourFolderName\\SQLite.db");
    }

    public DbSet<YourEntity> Pluto { get; set; }

}

Solution 2:[2]

You should modify to "Data Source=./data/database/sqlite.db"

"DefaultConnection": "DataSource=./data/database/sqlite.db"

Solution 3:[3]

First of all, as other suggested, you need to install the Microsoft.EntityFrameworkCore.Tools nuget package.

Then open package manager console in visual studio as follows.

Package Manager console in Visual Studio 2022

If you use Developer Power shell, it will not work.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MarGraz
Solution 2 tituszban
Solution 3 VivekDev