asp.netsqliteentity-framework-coreef-core-5.0

Entity Framework Core SQLite How to use relative Data Source


In a current Project of mine I am using Entity Framework Core together with SQLite in an ASP.Net-Project.

My Problem is, that the Database in the project-files is used, instead of the one in the ./bin-Directory

I followed the instructions of the docs.microsoft-page to create the database:

https://learn.microsoft.com/de-de/ef/core/get-started/overview/first-app?tabs=visual-studio

This is the Connectionstring I am using.

protected override void OnConfiguring(DbContextOptionsBuilder options)
    => options.UseSqlite("Data Source=MySqliteDatabase.db");

I let the created Database be copyied over, when newer.

I browsed through a number of pages, looking for ways to provide a relative Database path, but I couldnt find a solution to this. It either still uses the project-DB-File, or it wont create the new Database, because it cant be opened, or so.

Does anyone have a solution to this? I noticed that Entity-Framework-Core-5 is kind of a new release, could this be a bug or similar of this particular version?


Solution

  • Thanks @Sergey and @ErikEJ.

    So to solve this, I really needed to provide the full path of the directory. Since Directory.GetCurrentDirectory returned the wrong path, that is, the path to the project-directory instead of the /bin/Debug/... , I looked at the path that is named in the Config-File, as @Sergey suggessted, using the following Code:

    AppDomain.CurrentDomain.SetupInformation.ApplicationBase
    

    I got this from the following Stackoverflow page: How to find path of active app.config file?

    It said there, to access the ConfigurationFile-Property, but for ASP.Net it is ApplicationBase I guess.

    In there was the correct path, the one of the /bin/Debug/... .

    Put together, my new Method looked like this:

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        string databasePath = $"{AppDomain.CurrentDomain.SetupInformation.ApplicationBase}MySqliteDatabase.db";
        options.UseSqlite($"Data Source={databasePath}");
    }
    

    This works for me as intended, thanks alot for the support, maybe this will help someone else as well.