I'm developin an App using Xamarin.Android in C#, and I'm using Sqlite-net to manage the database, for now I'm using a model class (Animal) to define the table fields:
[Table("Animais")]
public class Animal
{
[PrimaryKey, MaxLength(20)]
public long AnimalId { get; set; }
[MaxLength(100)]
public string AnimalName {get; set; }
}
And I'm using this to Select all the Animals in the Database:
public List<Animal> SelectAll()
{
try
{
using (var conn = new SQLiteConnection(System.IO.Path.Combine(Database.PATH, Database.DB_NAME)))
{
return conn.Table<Animal>().ToList();
}
}
catch (SQLiteException ex)
{
Log.Info(TAG, "Houve um erro ao listar os animais: " + ex.Message);
return new List<Animal>();
}
}
But I have many others table in my database, and I dont want to create a single method to every Select, Insert or Update to each table, what can I do to create a generic SelectAll() where I can pass any model to query? For the Insert and Update operations I'm using object type, I don't know if this is the best approach but here it is:
public bool Insert(object b)
{
try
{
using (var conn = new SQLiteConnection(System.IO.Path.Combine(Database.PATH, Database.DB_NAME)))
{
conn.Insert(b);
return true;
}
}
catch (SQLiteException ex)
{
Log.Info(TAG, "Houve um erro ao adicionar um novo registro no banco de dados: " + ex.Message);
return false;
}
}
Can you guys help me with this? Improvements will be very welcome since I'm new to C#... Thank you very much!
SOLUTION EDIT:
Base class
class BaseDao<T> where T : new()
{
public bool Insert(T entity)
{
try
{
using (var conn = new SQLiteConnection(System.IO.Path.Combine(Database.PATH, Database.DB_NAME)))
{
conn.Insert(entity);
return true;
}
}
catch (SQLiteException ex)
{
Log.Info(TAG, "Houve um erro ao adicionar um novo registro no banco de dados: " + ex.Message);
return false;
}
}
public List<T> SelectAll()
{
try
{
using (var conn = new SQLiteConnection(System.IO.Path.Combine(Database.PATH, Database.DB_NAME)))
{
return conn.Table<T>().ToList();
}
}
catch (SQLiteException ex)
{
Log.Info(TAG, "Houve um erro ao listar os registros: " + ex.Message);
return new List<T>();
}
}
}
Child class:
class AnimalDao : BaseDao<Animal>
{
}