我有一个简单的实体:
[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。
我有同样的问题,刚刚找到答案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,你可以使用它
您可以使用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中可用。