Christian Graf
Christian Graf

Reputation: 406

WF8 & C# & SQLite & autoincrement & Fail

I try to use the SQLite Library for WP8.

I defined a table:

class ShoppingItem
{
  [SQLite.PrimaryKey]
  public int Id {get; set;}
  public string Name {get; set;}
  public string Shop {get; set;}
  public bool isActive {get; set;}
}

According to http://www.sqlite.org/autoinc.html a value is assigned to Id automatically by sqlite, if no value for Id has been given. Right?

So I try to insert new entries by

using (var db = new SQLiteConnection(m_DatabasePath)) {
    db.Insert(new ShoppingItem() {
      Name = anItem,
      Shop = aShop,
      isActive = aIsActive,
    });
}

When I insert a first item, it gets the ID 0. Well, why not. When I insert a second item, i get a SQLiteException with the awesome message "Constraint". So how can I insert a new entry without giving an id?

btw.: As an alternative solution, I tried to add a null value to id, but this resulted in a compilation error. :(

...
db.Insert(new ShoppingItem() {
  Id = null, // <- does not compile
  Name = anItem,
...

Upvotes: 3

Views: 1257

Answers (1)

CL.
CL.

Reputation: 180300

Your ShoppingItem does not know that the field is autoincrementing, so it assigns a default value of zero.

Use:

[SQLite.PrimaryKey, SQLite.AutoIncrement]
public int Id {get; set;}

Upvotes: 4

Related Questions