Returning a list of generic entities
c#, entity-framework, generics
Solution
This should do the job, just use the `Set<T>` property of your context:
public List<T> GetEntities<T>() where T : class
{
return db.Set<T>().ToList();
}
However, you probably want to keep this function returning an `IQueryable<T>` rather than a `List<T>` so you can continue to benefit from deferred execution. So the method becomes:
public IQueryable<T> GetEntities<T>() where T : class
{
return db.Set<T>();
}
And call it like this:
List<Customer> listOfCustomers = GetEntities<Customer>();
Or with the `IQueryable<T>` version:
IQueryable<Customer> listOfCustomers = GetEntities<Customer>();
Which you can now query properly:
IQueryable<Customer> allCustomers = listOfCustomers;
List<Customer> onlyBobs = allCustomers
.Where(c => c.Name = "Bob")
.ToList();
Problem
``` public List<Customer> GetAllCustomers() { List<Customer> listOfCustomers = db.Customer.ToList(); return listOfCustomers; } ``` I have a database with three tables (entities): Customer, Event and Venue. As you can see I am returning a list containing Customers but I would like to know if there is a way that I can return the entities in the list as something more generic. This would allow me not to be forced having separate get methods for all entities. I have searched the web but found nothing that was applicable when using lamdba syntax. Your help is greatly appreciated!