3

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.

1

2 Answers 2

1

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})";
Sign up to request clarification or add additional context in comments.

1 Comment

seems like there's no way to do this just using a parameter, but this works. Thanks
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.