Xamarin Sqlite Insert 不返回最后一个主键 ID

spr*_*t12 3 sqlite xamarin android-sqlite sqlite-net

我有一个简单的实体:

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

    [Indexed(Name = "IDX_History", Order = 1, Unique = true)]
    public int Prefix { get; set; }

    [Indexed(Name = "IDX_History", Order = 2, Unique = true)]
    public int Stem { get; set; }

    [Indexed(Name = "IDX_History", Order = 3, Unique = true)]
    public int Suffix { get; set; }

    [Indexed(Name = "IDX_Favourite")]
    public bool IsFavourite { get; set; }

    public DateTime LastViewed { get; set; } = DateTime.Now;
}
Run Code Online (Sandbox Code Playgroud)

如果它是新的,我正在尝试进行插入,或者如果它已经存在,则获取最后插入的 id:

public static int SaveSolutionToHistory(Solution sol)
{
    lock (_db)
    {
        var existingHistory = _db.Table<History>().FirstOrDefault(h => h.Prefix == sol.Prefix.Id 
            && h.Stem == sol.Stem.Id 
            && h.Suffix == sol.Suffix.Id);

        if (existingHistory != null)
        {
            existingHistory.LastViewed = DateTime.Now;
            _db.Update(existingHistory);
            return existingHistory.Id;
        }

         _db.Insert(new History
        {
            Prefix = sol.Prefix.Id,
            Stem = sol.Stem.Id,
            Suffix = sol.Suffix.Id
        });

        return _db.ExecuteScalar<int>("SELECT last_insert_rowid()");
    }
}
Run Code Online (Sandbox Code Playgroud)

顶部在返回现有条目的 id 时工作正常,但由于某种原因,插入代码在返回最后插入的主自动增量 id 时总是返回1(如方法 XML 注释中所述):

     _db.Insert(new History
    {
        Prefix = sol.Prefix.Id,
        Stem = sol.Stem.Id,
        Suffix = sol.Suffix.Id
    });
Run Code Online (Sandbox Code Playgroud)

这将返回正确的 id:

return _db.ExecuteScalar<int>("SELECT last_insert_rowid()");
Run Code Online (Sandbox Code Playgroud)

像这样进行两次点击或以非强类型方式进行操作对我来说似乎效率低下。有没有原因_db.Insert不返回正确的 ID?

我使用的是 VS 2015,带有 HAXM 和 Marshmallow x86_64 Google API Image。

小智 5

我遇到了同样的问题,刚刚在这里找到答案,完整的 xml 注释是:

//
// Summary:
//     /// Inserts the given object and retrieves its /// auto incremented primary key
//     if it has one. ///
//
// Parameters:
//   obj:
//     /// The object to insert. ///
//
// Returns:
//     /// The number of rows added to the table. ///
Run Code Online (Sandbox Code Playgroud)

“检索”摘要的意思是它更新您传递给它的对象中 PK 字段的值,因此如果您想要最后插入的 id,您可以使用它