简体   繁体   中英

Returning a list of generic entities

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!

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM