4
votes

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!

1
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
If you also want generic queries, check this out: stackoverflow.com/questions/29050400/…xleon

1 Answers

3
votes

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!