SQLite.Net Update generating error "it has no PK"
Asked Answered
I

1

6

I'm using Lync syntax in a PCL using Xamarin.

public class settings
{

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

    public string user_name { get; set; }
    public string password { get; set; }
    public string server { get; set; }

}

void CreateTables()
{
    database.CreateTable<settings>();
}

void Insert()
{    
     settings s = new settings();
     s.server = "<none>"
     s.user_name = "";
     s.password = "";
     database.Insert(s)
}

void Update()
{
     settings s = database.Table<settings>().FirstOrDefault();
     s.server = server_address.Text;
     s.user_name = user_name.Text;
     s.password = pass.Text;
     database.Update(s)
}

I get "Cannot update settings: it has no PK" when updating, but inserting works fine. I'm using Xamarin in a PCL referencing SQLite.net. I'm new to SQlite and Xamarin, so please be verbose when asking for more detail.

UPDATE - RESOLVED

The class is in the same namespace as the place I create an instance of the database object. Simply adding the "Sqlite" to my attribute fixed the issue which is really strange.

[SQLite.PrimaryKey, SQLite.AutoIncrement]
Icken answered 23/7, 2015 at 14:19 Comment(4)
does the record "s" have a PK set, or is it empty?Imperceptive
It shows 0, only a single record. I just did a var s = database.Table<settings>(); and looked at intelisense and the PK property is set to null and HasAutoIncPK = false. It looks like its ignoring the attributes...any idea?Icken
could you fix this?Ophthalmologist
@f Thank u thanks uCoagulum
E
0

I have been stocked for a week now on this problem and even the above solution is not working for me... I think that the Id does not increments automatically, that's why it says :cannot update ... What actually works for me is incrementing the PK (Id) manually...as follows.

persons.Id++;

At the moment of verifying and inserting data into the database, I just added the above code and it updated successfully.

private async void Register_Student(object sender, EventArgs e){... ... 

if(!string.Equals(newPassword.Text, rePassword.Text)){ 

warningLabel.Text = "Enter same pwd"; ... 
}
else{ 

    persons.Id++; //solution that worked for me at insertion level
    persons.UserName = newUsername.Text; //Text entered by the user
    }...
} 

Thanks...

Ellipsis answered 25/7, 2022 at 0:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.