首页 > 解决方案 > Xamarin.Forms sqlite-net-pcl 不使用值填充查询结果

问题描述

我正在使用 Visual Studio Mac 8.3.2 和 Xamarin.Forms 4.2.0 创建适用于 iOS 和 Android 的应用程序。作为数据库接口库,我使用的是 sqlite-net-pcl 1.6.292。我尝试了旧版本,但结果是一样的。

在 iOS 上一切正常。查询正确返回预期结果。在 Android 上,我得到了正确数量的结果记录,但结果值始终为 0 或空。

这里有一些代码

public class ewCatAbstract
{
    [PrimaryKey]
    public int id { get; set; }
    public string Name { get; set; }
    public string NoOfObjects { get; set; }
    public string ImageName { get; set; }

    public IEnumerable<ewCatAbstract> GetCategories()
    {
        var fieldName = Globals.dbFieldName(); // returning field name depending on currect language, e.g. nameEng

        var list = Globals.dbConnection.Query<ewCatAbstract>(
            "SELECT ewCat.id, ewCat." + fieldName + " AS Name, COUNT(ewObject2Category.id) AS NoOfObjects, " +
            "CASE WHEN ewCat.id = 2 THEN 'a.png' WHEN ewCat.id = 3 THEN 'b.png' ELSE '?' END AS ImageName " +
            "FROM ewCat, ewObject2Category " +
            "GROUP BY ewCat.id, ewObject2Category.category " +
            "HAVING ewObject2Category.category = ewCat.id " +
            "ORDER BY ewCat.sort");

        // debug code followng
        Console.WriteLine("ewCatAbstract GetCategories: {0} ", list.Count);

        foreach (var element in list)
        {
            Console.WriteLine("mybase: Type is {0}", element.GetType());
            Console.WriteLine("id " + element.id);
            Console.WriteLine("name " + element.Name);
        }

        return list;
    }
}

返回的记录数是正确的。在循环中运行时,我看到每个返回元素的正确类类型,但在打印“id”和“Name”值时,“id”始终为 0,“Name”字符串始终为空字符串。

可以打开与数据库的连接。我在这里没有得到任何错误。否则我不会得到正确数量的结果。请注意:代码在 iOS 上运行正常。它在Android下失败了。任何想法将不胜感激。

更多信息: sqlite 数据库是一个预先填充的数据库。我将数据库文件复制到“资产”文件夹中,并通过以下代码打开它。

public SQLite.SQLiteConnection CreateConnection()
{
    var sqliteFilename = AppResources.EwAppDatabase; // fetching file name from AppResources
    string documentsDirectoryPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
    var path = Path.Combine(documentsDirectoryPath, sqliteFilename);

    // This is where we copy in our pre-created database
    if (!File.Exists(path))
    {
        using (var binaryReader = new BinaryReader(global::Android.App.Application.Context.Assets.Open(sqliteFilename)))
        {
            using (var binaryWriter = new BinaryWriter(new FileStream(path, FileMode.Create)))
            {
                byte[] buffer = new byte[2048];
                int length = 0;
                while ((length = binaryReader.Read(buffer, 0, buffer.Length)) > 0)
                {
                    binaryWriter.Write(buffer, 0, length);
                }
            }
        }
    }
    var conn = new SQLite.SQLiteConnection(path);

    return conn;
}

我使用数据库只读。我不是在给它写信。

标签: androidxamarinxamarin.formssqlite-net-pcl

解决方案


推荐阅读