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
The error is self-explanatory. T
must have a public parameterless constructor. The following could help you hopefully
where T : new()
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With