4

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!

  • Can you include the entire method that contains your line of code using generic types? How are you declaring `T`? As a side note, you don't need to create a new `SQLiteConnection` every time you access the database, in fact it is considered better practice to use a singleton connection. – dylansturg Mar 29 '16 at 11:43
  • If you also want generic queries, check this out: http://stackoverflow.com/questions/29050400/generic-repository-for-sqlite-net-in-xamarin-project/29856945#29856945 – xleon Mar 30 '16 at 12:48

1 Answers1

3

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!

Artem Zelinskiy
  • 2,201
  • 16
  • 19
  • 1
    Disposing the connection can sometimes throw if other parallel queries occur at the same time (if you use async queries). I would use just one connection that would keep open in whole app live cycle instead – xleon Mar 30 '16 at 13:02
  • @xleon Thats true, and i agree with you, that it is better to use one connection. But Benjamin's current implementation does not utilize this approach. So in case, when you do not reuse connection, you should dispose it ASAP and utilize "try-with-resources". – Artem Zelinskiy Mar 31 '16 at 09:27