S Kirchner
S Kirchner

Reputation: 123

SQLite Xamarin deleting error because there is no PK

I made an app with a sqliteDB. But I always get an error when I wanna delete something. Here is my code: model:

    class Einkauf
    {
       private int _id;

        [PrimaryKey, AutoIncrement]
        public int Id
        {
            get
            {
                return _id;
            }
            set
            {
                _id = value;
            }
        }

        [MaxLength(100)]
        public string EssenName { get; set; } 

        public int Stueckzahl { get; set; }
    }

delete function:

    public partial class EinkaufAdd : ContentPage
    {
        private SQLiteAsyncConnection _connection;
        private ObservableCollection<Einkauf> _einkauf;

        public EinkaufAdd ()
        {
            InitializeComponent ();

        }

        private async void Button_Clicked(object sender, EventArgs e)
        {
            var response = await DisplayAlert("Achtung", "Wollen sie wirklich 
            alle Einträge löschen?", "Ja", "Nein");
            if (response == true)
            {
               //SQLITE
                _connection = DependencyService.Get<ISQLiteDb>().GetConnection();
                await _connection.CreateTableAsync<Einkauf>();
                var einkauf = await _connection.Table<Einkauf>().ToListAsync();
                await _connection.DeleteAsync(einkauf);
            }
        }

When I click the button, I get an error, called:

"System.NotSupportedException: "Cannot delete List`1: it has no PK"

". Its a "delete all" button just fyi.can anybody help me?

Debugginig tells me that the "einkauf" object has an id,essenname and all of this stuff.

Upvotes: 0

Views: 1030

Answers (2)

Petar_FX
Petar_FX

Reputation: 11

Had the same problem, I solved this way:

await _connection.DeleteAllAsync<Einkauf>();

Upvotes: 0

Jason
Jason

Reputation: 89092

the Delete() method takes a single object as an argument. You are trying to delete an entire list

// this returns a list of every item in the table
var einkauf = await _connection.Table<Einkauf>().ToListAsync();
await _connection.DeleteAsync(einkauf);

to delete them all, iterate through the list instead

foreach (var x in einkauf) {
  await _connection.DeleteAsync(x);
}

Upvotes: 1

Related Questions