jeudi 23 avril 2015

How can I make this SQLite query using the SQLite WP8.1 lib?

I'm using the SQLite for Windows Phone 8.1 library and I can't get the QueryAsync method to work.

Let's say I have a table called "Items" with this structure:

  • ID
  • ParentID
  • [Other data columns...]

Given a row, I want to get the total number of elements in the directory tree that has that row as the tree root.

I mean, in pseudo-code:

CountItems(rootID)
total = 0
children = SQLQuery(SELECT ID FROM Items WHERE ParentID = rootID)
foreach (id in children)
    total += CountItems(id)
return total

Now, I can't find a way to get this query to work using the SQLite library. I tested the query using DB Browser for SQLite and it seems to work, but I can't get that list back in WinRT.

This is what I tried:

public static async Task<int> CountContainedItemsAsync(int rootID)
{
    int total = 0;
    List<int> childrenIDs = await DatabaseConnection.QueryAsync<int>("SELECT ID FROM Items WHERE ParentID = ?", rootID);
    foreach (int childID in childrenIDs)
    {
        total += await CountContainedItemsAsync(childID);
    }
    return total;
}

But for some reason, if for example I call this method on a folder that has 4 children, childrenIDs becomes a List with 4 0s instead of the 4 IDs of the contained elements.

If instead of the QueryAsync I use:

List<Item> test = await DatabaseConnection.Table<Item>().Where(item => item.ParentID == rootID).ToListAsync();

I get my list of 4 items and it works fine, but the problem is that I don't want to use this method to avoid wasting memory, I just want that List with the IDs of the children at each recursive call.

Am I using missing something with the QueryAsync method?

Thanks for your help!

Sergio

Aucun commentaire:

Enregistrer un commentaire