当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《Xamarin.AndroidSQLiteSQLiteConnection.Insert不返回插入对象的ID》经验,为你挑选了1个好方法。

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

我无法弄清楚我做错了什么.在此先感谢任何帮助,并抱歉(可能)愚蠢的问题.



1> dsnunez..:

但是,在插入新配方时,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"
    });

推荐阅读
路人甲
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有