【发布时间】: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