2013-03-18 41 views
3

我嘗試使用WP8的SQLite庫。WF8&C#&SQLite&autoincrement&Fail

予定義的表:

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

根據http://www.sqlite.org/autoinc.html,一個值被分配給由Id源碼自動如果Id沒有值已經給出。對?

所以我試圖通過

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

當我插入第一個項目中插入新的條目,它得到ID爲0那麼,爲什麼不呢? 當我插入第二個項目時,我得到一個帶有令人敬畏的消息「約束」的SQLiteException。 那麼,如何在不給ID的情況下插入新條目?

btw .: 作爲替代解決方案,我試圖給id添加一個空值,但是這導致了編譯錯誤。 :(

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

是您的ID在你的表自動增量中您的數據庫? – Guillaume 2013-03-18 10:02:44

+0

不,但我不認爲這是必要的,根據http://www.sqlite.org/autoinc.html – 2013-03-18 10:05:29

回答

4

ShoppingItem不知道該字段自增,所以它分配的默認值爲零

用途:

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

是的,它的工作原理,謝謝。 但我不明白爲什麼我必須添加'AutoIncrement'標誌,如AutoIncrement應該由SQLite自動完成?! 或者我的問題是C#的SQLite庫的問題? – 2013-03-18 10:48:26

+1

問題是C#自動分配了一個值。 – 2013-03-18 10:54:22