Forum Libraries, Components, and Plugins

Setting PrimaryKey with custom value.

So, I have to following table in my Xamarin app:

    [Table("Tech")]
    public class TechCache
    {
        #region Unique Id.

        [PrimaryKey, AutoIncrement]
        public int UniqueId { get; set; }

        #endregion Unique Id.
        public string Title { get; set; }
        public int AgeRequired { get; set; }
        #region Resources.

        [ForeignKey(typeof(ResourcesCache))]
        public int ResourcesId { get; set; }

        [OneToOne(CascadeOperations = CascadeOperation.All, ReadOnly = false)]
        public ResourcesCache Resources { get; set; }

        #endregion Resources.
        public int TechType { get; set; } = TechTypes.UNIT;
        public bool IsDisplayed { get; set; } = true;
        public bool IsStock { get; set; } = false;
        public string Icon { get; set; } = "na.png";
        public string InGameDescription { get; set; }

    }

However, i intend to add starter data to my app and be prepared for future updates so i wanted to store objects like this:

    new TechCache
    {
        UniqueId = 10000,
        Title = "mw",
        Resources = new ResourcesCache { Wood = 200, Gold = 120 },
        Icon = "mw.png",
        InGameDescription = "mw_desc",
        IsStock = false,
   }

And insert them like this:
Connection.InsertWithChildren(TechTreeData.GetInitialTechTree());

But when testing it out, the uniqueId is set to the next value that would go in the table (Example, if i have 5 items, the next id will be 6) and not the 10000 that i want, how can i tell the function to use the value i provide without removing the autoincrement functionality?

Answers

  • ColeXColeX Member, Xamarin Team Xamurai

    You can modify the sqlite_sequence table using sql command to set the value what you want .

    Example

    using (var db = new SQLiteConnection("foo.sqlite"))
    {
        db.CreateTable<LoginTable>();
    
        db.Execute("insert into sqlite_sequence (name, seq) values (?, ?);", new object[] { "LoginTable", 999 });
    
        // if LoginTable records already exist, then the `sqlite_sequence` record exists for this table and you need to update it...
        //db.Execute("update sqlite_sequence set seq = ? where name = ?;", new object[] { 999, "LoginTable"});
    
        var login = new LoginTable { info = "info1....", info2 = "info2....." };
        db.Insert(login);
        db.Insert(login);
        db.Insert(login);
        foreach (var item in db.Table<LoginTable>())
        {
            Console.WriteLine(item.id);
        }
    }
    

    Refer https://stackoverflow.com/a/45625420/8187800.

Sign In or Register to comment.