Primary Key does not autoincrement

jddjdd USMember ✭✭✭

Using SQLite-net-pcl, the primary key of my items are not autoincremented. What am I doing wrong?

class Position:

    public class Position : INotifyPropertyChanged, IComparable<Position>
    {
        ResourceManager rm = Strings.ResourceManager;
        public event PropertyChangedEventHandler PropertyChanged;

        [SQLite.PrimaryKey, SQLite.AutoIncrement]
        public int? ID { get; set; }
        public double Latitude { get; set; }
        public double Longitude { get; set; }
        public DateTime DateTimeGroup { get; set; }
        public PositionType PositionType { get; set; }

class PositionsSightsDatabase

    public class PositionsSightsDatabase
    {
        readonly SQLiteAsyncConnection database;

        public PositionsSightsDatabase(string dbPath)
        {
            database = new SQLiteAsyncConnection(dbPath);
            database.CreateTableAsync<Position>().Wait();
            database.CreateTableAsync<Sight>().Wait();
        }

        public Task<int> SavePositionAsync(Position item)
        {
            if (item.ID != 0 && item.ID != null)
            {
                return database.UpdateAsync(item);
            }
            else
            {
                return database.InsertAsync(item);
            }
        }

event to insert a position:

        async void OnNewCelestialPositionClicked(object sender, EventArgs args)
        {
            Position newPosition = await Position.BuildPositionAsync();
            await AlmicantaratXF.App.PositionsSightsDB.SavePositionAsync(newPosition);

When I look to the items, all IDs == null (or 0 if not nullable). Therefore I can not delete an item.

Best Answer

  • jddjdd US ✭✭✭
    Accepted Answer

    I solved the issue, I don't know exactly how. Maybe by deleting an old SQLite.cs class or making the key nullable: public int? ID {get; set;}
    Anyway the code above works. But I needed to delete the whole database to make it work.

Answers

  • jddjdd USMember ✭✭✭
    Accepted Answer

    I solved the issue, I don't know exactly how. Maybe by deleting an old SQLite.cs class or making the key nullable: public int? ID {get; set;}
    Anyway the code above works. But I needed to delete the whole database to make it work.

  • ColeXColeX Member, Xamarin Team Xamurai

    The value returned by database.Update()/Insert() is not an ID!!! its the number of rows updated/inserted.

    Check https://forums.xamarin.com/discussion/comment/353707/#Comment_353707

  • jddjdd USMember ✭✭✭

    Yes, I had seen this discussion.
    But I was reading the ID not in the database.InsertAsync(item) but in the ListView.ItemsSource as you see on the picture.

Sign In or Register to comment.