SQLiteAsyncConnection.InsertAsync(obj) 没有 return 正确的密钥

SQLiteAsyncConnection.InsertAsync(obj) does not return correct key

我们在 Xamarin.Forms 应用程序中使用 SQLite 数据库来持久化模型层中的业务对象。

业务对象看起来像

[SQLite.Table(nameof(MyBo))]
class MyBo
{
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }
    public string Name { get; set; }

    ... etc
}

通话中

int id1 = conn.InsertAsync(new MyBo(){ ID = 0, Name ="Foo" });
int id2 = conn.InsertAsync(new MyBo(){ ID = 0, Name ="Bar" });

将导致 id1 = 1id2 = 1

conn.Table<T>().ToListAsync() returns 具有正确 ID(1 和 2)的对象。

我错过了什么,我期待 InsertAsync 调用 return 正确的值,但它总是 returns 1!?

InserAsync 方法,不 return 对象 ID,它 return 添加的行数(在您的情况下是正确的 = 1)

来自回购来源:

/// <summary>
        /// Inserts the given object and retrieves its
        /// auto incremented primary key if it has one.
        /// </summary>
        /// <param name="obj">
        /// The object to insert.
        /// </param>
        /// <returns>
        /// The number of rows added to the table.
        /// </returns>
        public Task<int> InsertAsync (object obj)
        {
            return WriteAsync (conn => conn.Insert (obj));
        }

您可以使用 Insert 在数据库中插入行。如果 table 包含一个自动递增的主键,那么在插入后该键的值将对您可用:

var stock = new Stock()
{
    Symbol = "AAPL"
};

await db.InsertAsync(stock);

Console.WriteLine("Auto stock id: {0}", stock.Id);