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!

2
  • 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. Commented Mar 29, 2016 at 11:43
  • If you also want generic queries, check this out: stackoverflow.com/questions/29050400/… Commented Mar 30, 2016 at 12:48

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

2 Comments

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 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".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.