2016-11-02 81 views
1

我有一個簡單的實體: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。

回答

2

我有同樣的問題,只是找到了答案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,你可以使用

0

你可以使用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