[英]Xamarin.Android SQLite SQLiteConnection.Insert does not return inserted object's ID
我是Xamarin和C#的新手,並嘗試將一些示例數據插入到我的簡單配方數據庫中以測試purpourses。
但是,在插入新配方時, SQLiteConnection.Insert(data)
不會返回插入記錄的ID(請參見此處 ),而是每次都返回1
。
我的插入數據方法:
public static int insertUpdate(Object data) {
string path = DB.pathToDatabase ();
DB.createDatabase ();
try {
var db = new SQLiteConnection(path);
int inserted = db.Insert(data);
if (inserted != 0)
inserted = db.Update(data);
return inserted;
}
catch (SQLiteException ex) {
return -1;
}
}
插入樣本數據:
int stand = insertUpdate (new Recipe {
Name = "Standard",
Author = "Aeropress Nerd",
Description = "The perfect recipe for your first cup",
Type = "Default"
});
insertUpdate (new Step { Action = "Pour", Duration = 10, Recipe = stand });
insertUpdate (new Step { Action = "Stir", Duration = 20, Recipe = stand });
insertUpdate (new Step { Action = "Steep", Duration = 15, Recipe = stand });
int inv = insertUpdate (new Recipe {
Name = "Inverted",
Author = "Aeropress Nerd",
Description = "A more advanced brew using the inverted method.",
Type = "Default"
});
我無法弄清楚我做錯了什么。 在此先感謝任何幫助,並抱歉(可能)愚蠢的問題。
但是,在插入新配方時,SQLiteConnection.Insert(數據)不會返回插入記錄的ID(請參見此處),而是每次都返回1。
我很確定你下載了一些nuget包或組件來包含SQLite功能到你的Xamarin.Android應用程序,它可能與本機實現略有不同。 然后,您應該參考特定文檔,了解您在Xamarin上使用的任何內容。
我猜測你正在使用這個組件 。 如果我錯了,請評論以糾正我的答案。 如果我是對的,你應該試試這個:
要插入的對象
class Row
{
public int Id { get; set; }
}
class Recipe : Row
{
//Recipe's properties
}
class Step : Row
{
//Step's properties
}
insertUpdate方法定義
public static int insertUpdate(Row data) {
string path = DB.pathToDatabase ();
DB.createDatabase ();
try {
var db = new SQLiteConnection(path);
int inserted = db.Insert(data); //will be 1 if successful
if (inserted > 0)
return data.Id; //Acording to the documentation for the SQLIte component, the Insert method updates the id by reference
return inserted;
}
catch (SQLiteException ex) {
return -1;
}
}
insertUpdate方法用法
//As Step and Recipe both are derived classed from Row, you should be able to use insertUpdate indistinctively and without casting
insertUpdate (new Step { Action = "Steep", Duration = 15, Recipe = stand });
int inv = insertUpdate (new Recipe {
Name = "Inverted",
Author = "Aeropress Nerd",
Description = "A more advanced brew using the inverted method.",
Type = "Default"
});
為什么在將數據插入數據庫后,您開始立即通過同一個對象更新數據。 這段代碼很可能是多余的。
if (inserted != 0)
inserted = db.Update(data);
return inserted;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.