【问题标题】:WF8 & C# & SQLite & autoincrement & FailWF8 & C# & SQLite & 自动增量 & 失败
【发布时间】:2013-03-06 14:47:52
【问题描述】:

我尝试使用 WP8 的 SQLite 库。

我定义了一个表:

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 赋值,sqlite 会自动为Id 赋值。对吧?

所以我尝试通过

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

当我插入第一个项目时,它的 ID 为 0。好吧,为什么不呢。 当我插入第二个项目时,我得到一个带有令人敬畏的消息“约束”的 SQLiteException。 那么如何在不提供 id 的情况下插入新条目呢?

顺便说一句: 作为替代解决方案,我尝试将空值添加到 id,但这会导致编译错误。 :(

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

【问题讨论】:

标签: c# sqlite windows-phone-8 auto-increment


【解决方案1】:

您的ShoppingItem 不知道该字段是自动递增的,因此它分配了一个默认值零。

用途:

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

【讨论】:

  • 是的,它有效,谢谢。但我不明白为什么我必须添加 AutoIncrement 标志,因为 AutoIncrement 应该由 SQLite 自动完成?!还是我的问题与 C# 的 SQLite 库有关?
  • 问题是C#自动赋值了。
猜你喜欢
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-13
  • 2017-03-07
  • 2019-09-09
  • 1970-01-01
相关资源
最近更新 更多