How do I provide a list as my parameter in sqlite-net

815 Views Asked by At

I am building a Xamarin Forms application and using Sqlite-net. I want to run a delete query that deletes all records that have a field in a list so something like below:

//usersToDelete is a list of Objects each representing a user.
List<int> idsToDelete = new List<int>();
foreach (var user in usersToDelete)
{
    idsToDelete.Add(user.Id);
}
string dbQuery = "DELETE FROM Users WHERE Id IN (?)";
var deleteCount = await LocalDatabaseConnection.ExecuteAsync(dbQuery, idsToDelete);

This does not work for me. It fails with the error Cannot store type: System.Collections.Generic.List1[System.Int32]. Does this mean I have build the string in code in palce of "(?)"? Or is there some way to provide this as a parameter.

2

There are 2 best solutions below

1
Serge On BEST ANSWER

try this

var utd= usersToDelete.Select(i=> i.Id.ToString()).ToArray();
string ids=string.Join(",",utd);
string dbQuery = $"DELETE FROM Users WHERE Id IN ({ids})";
0
thomasforth On

I don't know of a way to pass a List or an Array as a parameter into a written SQL query in SQLite-net except using the method in the answer that Serge has given.

This should also work,

//usersToDelete is a list of Objects each representing a user.
List<int> idsToDelete = new List<int>();
foreach (var user in usersToDelete)
{
    idsToDelete.Add(user.Id);
}

var deleteCount = await LocalDatabaseConnection.Table<Users>().DeleteAsync(x => x.idsToDelete.Contains(x.Id));

And makes better use of the capabilities of SQLite-net.