【问题标题】:AutoIncrement is not working with sqlite-net Client in windows phone universal AppAutoIncrement 不适用于 windows phone 通用应用程序中的 sqlite-net 客户端
【发布时间】:2014-10-29 11:22:25
【问题描述】:

我在我的 windows phone 通用应用程序中使用 sqlite-net for sqlite 我有以下具有表和列属性的类,并使用异步连接在 sqlite 中添加数据一切正常,但 Id 列也不是自动递增的是主键。还有其他人面临这个问题吗?以下是我的代码。

 [Table("Account")]
public class Account
{
    [PrimaryKey, AutoIncrement]
    [Column("Id")]
    public int Id { get; set; }

    [Column("FirstName")]
    public string FirstName { get; set; }

    [Column("LastName")]
    public string LastName { get; set; }

    [Ignore]
    public string FullName { get; set; }
  }


  SQLite.SQLiteAsyncConnection conn = new SQLite.SQLiteAsyncConnection("database.sqlite");
        var result = await conn.CreateTableAsync<Account>();

        var _accountList = new Account();
        _accountList.FirstName = "Name 1";
        _accountList.LastName = "------------";
        var result1 = await conn.InsertAsync(_accountList);

        _accountList = new Account();
        _accountList.FirstName = "Name 2";
        _accountList.LastName = "------------";
         result1 = await conn.InsertAsync(_accountList);

         var list = await conn.Table<Account>().ToListAsync();

         var item = list;

在读取表时,所有记录的 ID 始终为 0。有没有办法解决这个问题?

【问题讨论】:

    标签: sqlite windows-phone-8.1 win-universal-app sqlite-net


    【解决方案1】:

    这是一篇旧帖子,但也许我的回答可以帮助某人,几乎我希望如此。 首先将您的 Id 字段声明为可为空:

    [PrimaryKey, AutoIncrement]
    [Column("Id")]
    public int? Id { get; set; }
    

    重要的是你的主键可以为空,否则它会被发送到值为“0”的Insert方法并且SQLite不会改变一个已经存在的整数值,并且下一次插入你会收到一个错误,因为您正试图在表中添加另一个“0”索引。

    并且,在您的 CreateTable 部分中,指定 createFlags 参数,如果省略,则默认为“none”。

    我就是这样做的。 “_dbPath”是IsolatedStorage中数据库文件的路径:

    using (_connection = new SQLite.SQLiteConnection(_dbPath))
    {
       _connection.CreateTable<T>(SQLite.CreateFlags.ImplicitPK | SQLite.CreateFlags.AutoIncPK);
    }
    

    这将使您的 Id 字段成为索引主键,自动递增。

    【讨论】:

      【解决方案2】:

      我认为使用下面的代码会对你有所帮助。

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

      【讨论】:

      • 正是我需要的
      【解决方案3】:

      我遇到了类似的问题。

      尝试重置模拟器:

      Step 1: Goto C:\Program Files (x86)\Microsoft XDE\8.1\
      Step 2: Run XdeCleanup.exe
      

      然后重新运行您的应用程序。

      这发生在我身上,因为我创建了一个没有主键和自动增量的数据库,然后将其添加到代码中。但不知何故,没有PK&AI的状态被缓存在模拟器中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-25
        • 1970-01-01
        • 2011-12-09
        • 2020-04-06
        • 1970-01-01
        • 1970-01-01
        • 2014-11-25
        • 1970-01-01
        相关资源
        最近更新 更多