【问题标题】:Xamarin Sqlite Insert does not return last primary key idXamarin Sqlite 插入不返回最后一个主键 ID
【发布时间】:2017-12-20 07:18:07
【问题描述】:

我有一个简单的实体:

[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;
}

如果它是新的,我会尝试插入,如果它已经存在,我会尝试获取最后插入的 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()");
    }
}

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

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

这会返回正确的 id:

return _db.ExecuteScalar<int>("SELECT last_insert_rowid()");

对我来说,像这样进行两次点击或将其作为非强类型进行似乎效率低下。 _db.Insert 没有返回正确的 ID 是否有原因?

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

【问题讨论】:

    标签: sqlite xamarin android-sqlite sqlite-net


    【解决方案1】:

    我也遇到了同样的问题,刚刚找到答案here,完整的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. ///
    

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

    【讨论】:

    • 哇。谢谢你!由于没有完全阅读文档而只是看到“检索”这个词,我一直在追赶我的尾巴,以为这就是它返回的内容!
    【解决方案2】:

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

    public static void AddStock (SQLiteConnection db, string symbol) {
        var s = new Stock { Symbol = symbol };
        db.Insert (s);
        Console.WriteLine ("{0} == {1}", s.Symbol, s.Id);
    }
    

    这意味着 ID 将在对象字段 Id 中可用。

    https://components.xamarin.com/gettingstarted/sqlite-net

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      • 2016-06-27
      • 1970-01-01
      • 2014-06-19
      • 1970-01-01
      • 2012-04-05
      • 1970-01-01
      相关资源
      最近更新 更多