gpt4 book ai didi

c# - Xamarin.Android SQLite SQLiteConnection.Insert 不返回插入对象的 ID

转载 作者:太空宇宙 更新时间:2023-11-03 12:49:28 25 4
gpt4 key购买 nike

我是 Xamarin 和 C# 的新手,正在尝试将一些示例数据插入到我的简单配方数据库中以测试目的。

但是,当插入新配方时,SQLiteConnection.Insert(data) 不会返回插入记录的 ID(请参阅 here ),而是返回 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"
});

我不知道我做错了什么。在此先感谢您的帮助,并对这个(可能)愚蠢的问题表示抱歉。

最佳答案

However, when inserting a new recipe, the SQLiteConnection.Insert(data) does not return the ID of the inserted record as it should (see here), but instead returns 1 every time.

我很确定您下载了一些 nuget 包或组件以将 SQLite 功能包含到您的 Xamarin.Android 应用程序中,它可能与 native 实现略有不同。然后,无论您在 Xamarin 上使用什么,您都应该引用具体文档。

我的猜测是您正在使用 this component .如果我错了,请评论以更正我的答案。如果我是对的,你应该试试这个:

要插入的对象

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"
});

关于c# - Xamarin.Android SQLite SQLiteConnection.Insert 不返回插入对象的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34728992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com