Reputation: 2917
I recently moved across from SQLite.NET to SQLite-net-pcl due to the Android 7.0 SQlite issue.
In the process I have updated all my libraries and all is working well with regards to insert/drop etc.
The only issue I have is that every time I retrieve an item from the DB it always has an ID of 0. This is causing problems with updating items. Has anyone had this issue before?
[SQLite.PrimaryKey, SQLite.AutoIncrement]
public int ID { get; set; }
public string objectId { get; set; }
public DateTime createdAt { get; set; }
public DateTime updatedAt { get; set; }
public string Title { get; set; }
Thanks in advance.
Upvotes: 7
Views: 5878
Reputation: 135
Make sure that you're not using InsertOrReplace with an AutoIncrement primary key. It will always override item with id 0 and never insert a new one. -redent84
All database entries need to be added using await _database.InsertAsync(myClass);
Upvotes: 0
Reputation: 131
My problem was that I had an internal set for my ID property setter. This had to be public to work correctly.
I'd add this as a comment but alas... I don't have enough rep.
Upvotes: -1
Reputation: 3751
I have been struggling with the same issue here.
I was manually creating the tables to guarantee a smoother update process moving forwards rather than using the CreateTable
methods available.
The fix that I eventually stumbled upon was that I was using the wrong data type for my PRIMARY KEY column.
Wrong definition
[RecordIndexId] int PRIMARY KEY NOT NULL
Correct definition
[RecordIndexId] integer PRIMARY KEY NOT NULL
To add a little context there is a big different between the int
and integer
data types. Explained in this SO answer
Upvotes: 0
Reputation: 61
Please try using this, this worked for me
using SQLite.Net.Attributes;
[PrimaryKey, AutoIncrement]
public int? Id { get; set; }
Upvotes: 6
Reputation: 441
Had almost the same situation. with all rows returning id of 0
class ToDo : Java.Lang.Object
{
[PrimaryKey, AutoIncrement]
public int ID { get; }
except I simply had forgotten to type set; in the property.
one thing that might help someone with this sorta problem is using the GetMapping() method to get some info on the mapping used when CreateTable() is used to create the table. as example:
Toast.MakeText(this, db.GetMapping<ToDo>().TableName.ToString(), ToastLength.Long).Show();
Toast.MakeText(this, db.GetMapping<ToDo>().HasAutoIncPK.ToString(), ToastLength.Long).Show();
using this I found out that AutoIncrement (HasAutoIncPK = false) wasn't being set on my table.
Upvotes: 2
Reputation: 1
See if you created the table with the methods CreateComand(query)
and ExecuteNonQuery()
. If this is the case, create your table with the CreateTable<Type>()
method. The primary key and autoincrement attributes are initialized at the time of creating the table through said method
Upvotes: 0