Ben*_*bbs 3 c# android xamarin
我是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;
}
}
Run Code Online (Sandbox Code Playgroud)
插入样本数据:
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"
});
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚我做错了什么.在此先感谢任何帮助,并抱歉(可能)愚蠢的问题.
但是,在插入新配方时,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
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
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"
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3296 次 |
| 最近记录: |