Search code examples
xamarinsqlite.net

How to use InsertOrReplace in sqlite.net PCL?


I am using the PCL version of sqlite.net from here (https://github.com/oysteinkrog/SQLite.Net-PCL).

Here is my simple class.

    public class LogEntry
    {
      [PrimaryKey, AutoIncrement]
      public int Key { get; set;}
      public DateTime Date { get; set; }
    }

When a new instance of LogEntry is created, the Key is automatically set to 0. I set the Date to something and then call InsertOrReplace. The record does get saved in my database. The Key field gets the autoincrement value which happens to be 0 since it is the first record.

I then create a new instance of LogEntry (Key is automatically initialized to 0) and set the date to something else. I then call InsertOrReplace. Since there is an existing record with a Key of 0 that record gets updated.

What is the proper way to deal with this? I considered initializing the Key to -1, but that didn't seem to work either.

Does anyone have an example of this working?


Solution

  • I experienced the same issue as you are describing. Try

    var rowsAffected = Connection.Update(object);
    
    if(rowsAffected == 0) {
        // The item does not exists in the database so lets insert it
        rowsAffected = Connection.Insert(object);
    }
    
    var success = rowsAffected > 0;
    
    return success;
    

    I just tried above and it works as expected