Benjamin Ceustermans
Benjamin Ceustermans

Reputation: 43

Xamarin SQLite.NET Generic TableQuery

I use the component "SQLite.NET" in my Xamarin-project. I have several "models/classes" like "Document","Project". Each model has its own Table in SQLite.

To get the data from a table, i'm using the following technique:

List<Document> documents = new SQLiteConnection("..DB-path..").Table<Document>.ToList();

It works fine, but for each table I have to do the same code and only changing the Model-type in the code above.

Now I would like to write a generic method where I can do:

List<T> data = new SQLiteConnection("..DB-path..").Table<T>.ToList();

But unfortunately, I get the following error:

'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'SQLiteConnection.Table()'

Does anyone know a way to create a generic method for the problem above?

Thanks in advance!

Upvotes: 4

Views: 2969

Answers (1)

Artem Zelinskiy
Artem Zelinskiy

Reputation: 2210

You should add constraint to you function.

public List<T> GetData<T> () where T: new()
{
    using(var connection = new SQLiteConnection("..DB-path..")){
       return connection.Table<T>.ToList();
    }
}

Do not forget to dispose your DB connection!

Upvotes: 3

Related Questions