SQLite.NET PCL returning 0 in all instances of autoincrement primary key

556 views Asked by At

I am totally not getting this, because I have used this library in Xamarin apps for several years.

I have this base class that contains properties common in all db items:

public class BaseItem
{
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; } = 0;        // SQLite ID
    public long CreatedTimeSeconds { get; set; } = DateTime.Now.ToUnixTimeSeconds();
    public long ModifiedTimeSeconds { get; set; } = DateTime.Now.ToUnixTimeSeconds();
}

Now, I derive from it:

[Table("CategoryTable")]
public class Category : BaseItem
{
    public int CategoryTypeID { get; set; } = (int)CategoryType.Invalid;
    public string Name { get; set; } = string.Empty;
    public string Description { get; set; } = string.Empty;
}

Here's a simplified version of what I'm seeing:

public class DBWorld
{
    ISQLiteService SQLite { get { return DependencyService.Get<ISQLiteService>(); } }

    private readonly SQLiteConnection _conn;
    
    public DBWorld()
    {
        _conn = SQLite.GetConnection("myapp.sqlite");    
    }

    public void TestThis()
    {
        _conn.CreateTable<Category>();
        
        var category = new Category();
        category.Name = "This Should Work";
        
        int recCount = connection.Insert(category);
        // at this point recCount shows as 1, and category.ID shows as zero.
        // I thought Insert was supposed to set the autoincrement primary key 
        
        // regardless, it should be set in the database, right? So...
        var categoryList = connection.Query<Category>($"SELECT * FROM {DBConstants.CategoryTableName}");
        // at this point categoryList[0] contains all the expected values, except ID = 0        
    }
} 

I am obviously missing something, but for the life of me, I can't figure out what...

1

There are 1 answers

0
John Ureke On BEST ANSWER

Like so many other bizarre things that happen in the Visual Studio Xamarin world, when I went back later, this worked the way all of us expect. I guess Visual Studio was just tired and needed to be restarted.