Wojciech Szabowicz
Wojciech Szabowicz

Reputation: 4198

How can I point two different projects to the same SQLite db-file?

I have a simple question. I have 2 layers in my application, a front-end and data access layer, in different projects. I am creating a sqlite db in the data access layer by migration in data access layer and now I want to use a connection string. I am creating a context in the data access layer like this:

public class TodoDbContext : DbContext
{
    public DbSet<Activity> Activieties { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite(@"Data Source=todo.db");
    }
}

Looks simple right, db is created in data access layer project. But when I run front end project program is looking for a db but in a front end project folder.I have checke that by adding:

 var test = Directory.GetCurrentDirectory(); 

In above method. Also when I modify connection string to direct path like:

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite(@"Data Source=C:\Users\Administrator\Desktop\TodoList\TodoDataAccess\todo.db");
    }

It works, so my question is what can I do to change it?

Upvotes: 11

Views: 5576

Answers (1)

Jacek Blaszczynski
Jacek Blaszczynski

Reputation: 3269

To make accessing your app data easier just put it in well known folder. Based on your application name I assume that your app is a desktop one and stores user specific data in SQLite DB which should be accessible from different computers. Than location of DB should be determined as:

    var sqlitePath = Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), 
        @"<YourAppName>\todo.db");

This simplifies all application data management and makes location of the data on all computers users may be using consistent disregard of the way application is installed. Furthermore this guarantees that user will have full access rights to DB folder. In case your project has other functional requirements data location should be adjusted accordingly.

Upvotes: 8

Related Questions