I have installed the nuget package sqlite-net-pcl and I want to insert or update depending on the text on the button:
SQLiteConnection database = DependencyService.Get<ISQLite>().GetConnection();
database.CreateTable<Announcement>();
var announcement = new Announcement { AnnouncementTitle = Title, AnnouncementDate = Date, AnnouncementText = Message };
if (text == "Save") {
if (database.Insert(announcement) != -1) {
System.Diagnostics.Debug.WriteLine("INSERTED");
}
}
else {
if (database.Update(announcement) > 0) {
System.Diagnostics.Debug.WriteLine("UPDATED");
}
}
When I want to save it print INSERTED and I can see the new item in my list but when it comes to update it doesn't print anything and I don't get an error. I also tried the async methods and it didn't work
Thanks
Since you want to update you have to get the original entry from the database first. Now you don't have the Id
field (or how it is called in your model) entered, so it doesn't know what to update.
Update your code to do something like this, note: this is pseudo code since I am missing some details of your model and relevant knowledge of SQLite.
SQLiteConnection database = DependencyService.Get<ISQLite>().GetConnection();
database.CreateTable<Announcement>();
var announcement = new Announcement { AnnouncementTitle = Title, AnnouncementDate = Date, AnnouncementText = Message };
if (text == "Save") {
if (database.Insert(announcement) != -1) {
System.Diagnostics.Debug.WriteLine("INSERTED");
}
}
else {
var announcementToUpdate = database.Query<Customer>($"SELECT * FROM Announcement WHERE Id = '{originalId}'").
// update your 'announcementToUpdate' object with new values here
if (database.Update(announcementToUpdate) > 0) {
System.Diagnostics.Debug.WriteLine("UPDATED");
}
}
originalId
should be a variable with the announcement of the Id you're trying to edit.
So the key here to update is that you have to retrieve the record from the database first. Or create a new object with the Id
of the record that you want updated.