I am using Entity Framework to read/write data to the DB and wondering if there is a way to get the entities by type. For example: I have
Student table and
Classroom table (in reality, I have bunch of tables). I would like to get all the students by using the type or entity name. Basically I need something generic to read the data from the DB.
The solution I have is to use reflection to read the
DbContext properties that returns
IQueryable, but it seems there should be another way of doing it. If so, can someone tell me how to do it?
I need something like this:
Are you looking for this?
DbSet<T> allEntities = yourDbContext.Set<T>();
where you can replace
T with any of your entity types, e.g. with
DbSet<Student> allStudents = yourDbContext.Set<Student>();
and if you need the
IQueryable, just use
IQueryable<Student> allStudents = yourDbContext.Set<Student>().AsQueryable();
Please study the official MSDN documentation on
DbContext for more details and more properties and method on that class