mercredi 4 mars 2015

SQLite with mvvmcross

I have an SQLite database set up within my mvvmcross android application like this



public class DataService : IDataService
{
object dbLock = new object();
readonly ISQLiteConnection connection;

public DataService(ISQLiteConnectionFactory factory)
{
connection = factory.Create("mydatabase.db3; New=true; Version=3;PRAGMA locking_mode=EXCLUSIVE; PRAGMA journal_mode=WAL; PRAGMA cache_size=20000; PRAGMA page_size=32768; PRAGMA synchronous=off");
}


within my HomeviewViewModel, the database is set up and the tables inserted. There are no issues there.


When I come to insert into the database, any calls to connection.Execute results in the app crashing with an error to say that you can't execute on an unopened database.


The insert/update looks like this



public void AddOrUpdateContacts(List<Connections> contacts)
{
foreach (var sr in contacts)
AddOrUpdateContacts(sr);
}

public void AddOrUpdateContacts(Connections contact)
{
lock (dbLock)
{
using (var sqlcon = connection)
{
sqlcon.Execute(Constants.DBClauseSyncOff);
sqlcon.BeginTransaction();
try
{
if (sqlcon.Execute("UPDATE StoreItem SET Id=?, " +
"Name=?, Phone=?, InviteSent=?, InviteAccepted=?, CanShareWith=?, TypeOfContact=? WHERE Id=?",
contact.Id, contact.Name, contact.Phone, contact.InviteSent, contact.InviteAccepted, contact.CanShareWith, contact.TypeOfContact, contact.Id) == 0)
sqlcon.Insert(contact, typeof(Connections));
sqlcon.Commit();
}
catch (Exception ex)
{
#if DEBUG
Debug.WriteLine("Error in AddOrUpdateContacts - {0}--{1}", ex.Message, ex.StackTrace);
#endif
sqlcon.Rollback();
}
}
}
}


I've used this code in non-PCL and Xamarin.Forms apps without a hitch. When I check connection prior to the Execute call, it is correctly set.


Aucun commentaire:

Enregistrer un commentaire