Am attempting to delete all items from a sqlite database table accessed via nuget package sqlite-net-pcl(1.5.166-beta) for Xamarin.forms.
The method DeleteAllAsync, according to Visual Studio's code completion menu, takes a 'TableMapping Map' Can you help me find out what a 'TableMapping Map' is in this case?
Where could I find the documentation for the sqlite-net-pcl nuget package? There is no project page listed for it on nuget.
The code snippet below gives context and an incorrect call of DeleteAllAsync
public class ItemDb
{
readonly SQLiteAsyncConnection database;
public ItemDb(string dbPath)
{
database = new SQLiteAsyncConnection(dbPath);
database.CreateTableAsync<Item>().Wait();
}
internal void DeleteAll()
{
database.DeleteAllAsync(database.Table<Item>);
}
}
You just need to specify the Type to use DeleteAllAsync, and it will remove all items from the table.
internal async Task DeleteAll()
{
await database.DeleteAllAsync<Item>();
}
DeleteAllAsync is new in sqlite-net-pcl v1.5, and v1.5 is still in pre-release. The official documentation is here, and it will likely be updated to include DeleteAllAsync once v1.5 is promoted to stable:
https://github.com/praeclarum/sqlite-net/wiki
Faster Method
A faster way to delete all items in a table is to drop the table and re-create it (assuming the tables has many items).
internal async Task DeleteAll()
{
await database.DropTableAsync<Item>();
await database.CreateTableAsync<Item>();
}
Complete Example
Here is a complete example that helps improve performance and avoid multithreading problems.
public class ItemDb
{
readonly SQLiteAsyncConnection database;
readonly SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);
public ItemDb(string dbPath)
{
database = new SQLiteAsyncConnection(dbPath);
}
internal async Task DeleteAllItems()
{
await semaphoreSlim.WaitAsync().ConfigureAwait(false);
await Initialize<Item>().ConfigureAwait(false);
try
{
await database.DropTableAsync<Item>().ConfigureAwait(false);
await database.CreateTableAsync<Item>().ConfigureAwait(false);
}
finally
{
semaphoreSlim.Release();
}
}
async Task Initialize<T>()
{
if (!DatabaseConnection.TableMappings.Any(x => x.MappedType.Name == typeof(T).Name))
{
await DatabaseConnection.EnableWriteAheadLoggingAsync().ConfigureAwait(false);
await DatabaseConnection.CreateTablesAsync(CreateFlags.None, typeof(T)).ConfigureAwait(false);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With