I initially thought that you cannot get entities only with type, but looking at Matt, you can. So this answer is probably not the best ...
The main idea is to get an IEnumerable<object> list, where each IEnumerable<object> is an entity in our model. The reason we should use the plain old object is because we want it to return different objects that are not related to each other. But this is not so bad, because when you scroll through each object, you can pass it to a specific object if you need to.
First we create a method that returns this list:
private static List<IEnumerable<object>> AllEntities(MyEntities db) { List<IEnumerable<object>> list = new List<IEnumerable<object>>(); list.Add(db.UserRole); list.Add(db.UserAccountRole); list.Add(db.UserAccount); return list; }
We go to our DbContext because it will be used when we actually start the loop through IEnumerables , which happens outside of this method. Therefore, we cannot create a DbContext here, and then Dispose it.
Now we can use this method to process all our objects:
using (var db = GetMyEntities()) { List<IEnumerable<object>> recordsList = AllEntities(db); foreach (IEnumerable<object> records in recordsList) { foreach (object record in records) {
And it's all. In terms of SQL, it will do something like SELECT * FROM TABLE_NAME for each iteration of the foreach outer loop. This means that it does not cache the data inside List<IEnumerable<object>> , and every time you use AllEntities , it gets fresh data from the database.
source share