I'm working on a Universal App using SQLite, and I've been using this tutorial along with SQLite for Windows Runtime (Windows Phone 8.1) and sqLite-net to get started.
I'm using this to check if the database exists:
bool exists = true;
try {
var file = await ApplicationData.Current.LocalFolder.GetFileAsync( "database.db" );
} catch {
exists = false;
}
and if not running some insert queries to populate default data:
if( !exists ) {
var conn = new SQLiteConnection( "database.db );
conn.CreateTable<MyClass>();
MyClass.Insert( "Default data value" );
}
where MyClass is
[Table( "MyClass" )]
public class MyClass {
public MyClass() {
this.ID = -1;
this.Name = string.Empty;
}
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
[NotNull]
public string Name { get; set; }
internal static void Insert( string Name ) {
var myclass = new MyClass();
myclass.Name = Name;
var conn = new SQLiteConnection( "database.db" );
try {
if( myclass.ID == -1 ) conn.Insert( myclass );
} catch { }
}
public async static Task<List<MyClass>> List() {
var conn = new SQLiteAsyncConnection( "database.db" );
var rs = conn.Table<MyClass>().OrderBy( t => t.ID );
return await rs.ToListAsync();
}
}
The problem is every time I do a fresh deploy (after uninstalling from my test device), and the code correctly determine the database doesn't exist and performs the inserts, I'm left with an increasing number of records. More specifically, I'm doing an insert of four default values, but at my last deploy that table currently has 124 records (meaning I've deployed 31 times) and looking at the data, it's the same four values repeated. Stepping through the code, only four inserts are occurring, as expected.
It seems like the database is being cached somewhere. I've run the Windows Phone Power Tools and verified there are no files after uninstall. Am I missing something here?
I had a similar problem some time ago (although not with SQLite). Try to check the "Disable automatic backup/restore" checkbox in WMAppManifest.xml (Packaging tab).
In general though,
new SQLiteConnection( "database.db" );
by itself does not guarantee a new file being created and your code doesn't currently ensure the file does not already exist: you are catching all exceptions while your condition is only covered byFileNotFoundException
- theGetFileAsync
may fail for other reasons than the file not existing. I would suggest catching theFileNotFoundException
exception to begin with, and possibly also creating the file explicitly in code.