我有一個簡單的實體:Xamarin sqlite的插入不返回最後一個主鍵ID
[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,但由於某些原因,插入代碼總是返回時,它應該返回最後插入自動增量主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。