Reputation: 311
I have a sqlite class with a few entities and I don't want to create a method for every type of entity like this:
public async List<Sheep> GetSheeps()
{
return database.Table<Sheep>().ToListAsync();
}
public async List<Goat> GetGoats()
{
return database.Table<Goat>().ToListAsync();
}
I want to create an interface (e.g. IEntity
) and inherit it my POCO classes of sheep and goat.
Then I want to create just one generic method to get the items.
This is what I tried, it says I cannot use T
as a type:
public async T GetEntities<T>()
{
if (typeof(T) == IEntity)
return database.Table<T>().ToListAsync();
}
Maybe I dind't completely understand what T
is..
Any help appreciated.
Upvotes: 0
Views: 100
Reputation: 81583
Nearly...
await
an async
callasync
await
pattern, you will need to return a Task
T
you will have to declare the List<T>
as a generic parameter of your task i.e Task<List<T>>
typeof(T) == IEntity
use a constraint where T : IEntity
Code
public async Task<List<T>> GetEntities<T>() where T : IEntity
{
return await database.Table<T>().ToListAsync();
}
Though, some things to consider
IEntity
using
statement when dealing with a db (and not hold a reference to it)Using
var myLovelyHorseList = await GetEntities<Horse>();
Update
Its a bit early in the morning for me and i am with out a coffee and cant test this. but i think you might need the new()
constraint, and your classes will have to have a parametesless constructor
where T : IEntity, new()
Upvotes: 3