Entity Framework : get all entities with specific type

c# database entity-framework entity-framework-6 orm

Question

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:

dbContext.GetEntities<T>()

or

dbContext.GetEntities(Type entityType)
1
0
3/20/2017 4:57:28 PM

Popular Answer

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 Student:

DbSet<Student> allStudents = yourDbContext.Set<Student>();  

and if you need the IQueryable, just use .AsQueryable():

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

5
3/18/2017 10:47:19 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow