Skip to content

Instantly share code, notes, and snippets.

@icebeam7
Created December 5, 2019 00:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save icebeam7/78e5a78417b2c86105d1ea84501ef726 to your computer and use it in GitHub Desktop.
Save icebeam7/78e5a78417b2c86105d1ea84501ef726 to your computer and use it in GitHub Desktop.
HarryPotterApp: DatabaseContext.cs
using System.Threading.Tasks;
using System.Collections.Generic;
using SQLite;
using HarryPotterApp.Models;
namespace HarryPotterApp.Data
{
public class DatabaseContext
{
private readonly SQLiteAsyncConnection connection;
public DatabaseContext(string dbPath)
{
connection = new SQLiteAsyncConnection(dbPath);
connection.CreateTableAsync<HPCharacter>().Wait();
}
public async Task<List<T>> GetItemsAsync<T>() where T : new()
{
return await connection.Table<T>().ToListAsync();
}
public async Task<List<T>> FilterItemsAsync<T>(string table, string condition) where T : new()
{
return await connection.QueryAsync<T>($"SELECT * FROM {table} WHERE {condition}");
}
public async Task<T> GetItemAsync<T>(string id) where T : new()
{
return await connection.FindAsync<T>(id);
}
public async Task<int> SaveItemAsync<T>(T item, bool isInsert) where T : new()
{
return (isInsert)
? await connection.InsertAsync(item)
: await connection.UpdateAsync(item);
}
public async Task<int> DeleteItemAsync<T>(T item) where T : new()
{
return await connection.DeleteAsync(item);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment