Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method with sqlite-net

I want to make a simple repository and underneath there is the method I have used:

public static List<T> GetAll()
{
    return _dbConnection.Table<T>().ToList();
}

But I am encountering an 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 'SQLite.SQLiteConnection.Table<T>()'

I use SQLite wrapper sqlite-net.

Ofc my class is generic:

class FeedRepository<T> : IFeedRepository<T>, IDisposable where T : IFeed
like image 815
rechandler Avatar asked Nov 16 '13 10:11

rechandler


3 Answers

The error is self-explanatory. T must have a public parameterless constructor. The following could help you hopefully

where T : new()
like image 194
Ondrej Janacek Avatar answered Nov 01 '22 23:11

Ondrej Janacek


It sounds like you just need to add another constraint to T - the Table<T>() method appears to want the new() constraint, so you'll need to add that to your constraint list too:

class FeedRepository<T> : IFeedRepository<T>, IDisposable where T : IFeed, new()

At that point, the compiler will know that the T type parameter for your class satisfies the constraint for the T type parameter of the Table method, and it should be fine. Of course, this means that anyone using your FeedRepository<T> class can only do so with non-abstract types with a public constructor... but then that's a natural limitation of what you're trying to achieve.

like image 10
Jon Skeet Avatar answered Nov 01 '22 23:11

Jon Skeet


Apparently, the Table<T> method has a type constraint of new(). However, the generic type parameter of FeedRepository<T> does not have such a constraint so you cannot use it directly in Table<T>.

You'll need to add a contraint to the FeedRepository<T>:

class FeedRepository<T> : IFeedRepository<T>, IDisposable where T : IFeed, new()
like image 2
Eren Ersönmez Avatar answered Nov 01 '22 23:11

Eren Ersönmez