I am using sqlite-net
in my project and have a helper class called SqLiteHelper. Inside this class I have a simple method that returns TableQuery
results as a List. Example:
public static class SqLiteHelper
{
public static List<Contact> GetTableQueryResults()
{
List<Contact> contacts;
using (var connection = new SQLiteConnection(App.DatabasePath))
{
connection.CreateTable<Contact>();
contacts = connection.Table<Contact>().ToList();
}
return contacts;
}
}
I want to make this method reusable to use it in the future in other context. For example when I will have another project with a different class then 'Contact'. I tried it myself by refactoring it to this:
public static IList<T> GetTableQueryResults<T>()
{
List<T> contacts;
using (var connection = new SQLiteConnection(App.DatabasePath))
{
connection.CreateTable<T>();
contacts = connection.Table<T>().ToList();
}
return contacts;
}
But the SQLiteConnection.Table<> method throws the following error:
Any ideas how I can make this method reusable?
I had a look here but it's not in connection with SQLite
.
Provide the generic type constraint of T
as where T: new()
in your method. The new()
constraint lets the compiler know that any type argument supplied must have an accessible parameterless constructor.
Method:
public static IList<T> GetTableQueryResults<T>() where T : new()
{
List<T> contacts;
using (var connection = new SQLiteConnection(App.DatabasePath))
{
connection.CreateTable<T>();
contacts = connection.Table<T>().ToList();
}
return contacts;
}
Read about new
constraint at here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.