1

I have this code in App.xaml.cs:

    private SQLiteConnection dbCon;

    public void App_Startup(object sender, StartupEventArgs e)
    {
        SQLiteConnection.CreateFile("testdb.sqlite");

        dbCon = new SQLiteConnection("Data Source=testdb.sqlite;Version=3;");
        dbCon.Open();

        string query = "create table if not exists Settings(Key nvarchar(max), Value nvarchar(max));";
        SQLiteCommand command = new SQLiteCommand(query, dbCon);
        command.ExecuteNonQuery();
    }

This runs just fine... but then on ShellViewModel.cs I have this:

    public ShellViewModel()
    {
        dbCon = new SQLiteConnection("Data Source=testdb.sqlite;Version=3;");
        dbCon.Open();

        string query = "Select Value from Settings where (Key = 'isFirstTime')";
        SQLiteCommand command = new SQLiteCommand(query, dbCon);
        command.ExecuteNonQuery();

        //if(no information or first time)
        //      show registerationview.xaml
        //else
        this.ActivateItem(new MainViewModel()); // show main view.
    }

The thing is I get "Table not found" in the above code.

The only reason for this I could think about is the fact that App.xaml.cs is in the root directory of the project, while ShellViewModel.cs is inside the ViewModels folder, but I have no idea how to make it point to that specific database file in the root directory, if that's even the problem.

What is the problem/solution? I tried finding answers but all the questions were answered with 'possible causes to the problem', so they don't really help.

Asaf
  • 2,005
  • 7
  • 37
  • 59

1 Answers1

0

use Full path in all locations where working with SQLite database as below

string fullPath = Path.Combine(ApplicationDataBaseFolderPath, "testdb.sqlite");

SQLiteConnection.CreateFile(fullPath);

And

dbCon = new SQLiteConnection(String.Format("Data Source={0};Version=3;", fullPath));

You can use one of the answer for the Getting the application's directory from a WPF application SO Question and find the aplication directory and then combine that with Folder Name where your database should locate.

string ApplicationDataBaseFolderPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "AppData");
Community
  • 1
  • 1
Damith
  • 62,401
  • 13
  • 102
  • 153