How to get DbSet<SomeClass> (EF) from the dbContext using reflection?

c#, entity-framework, linq, reflection

Solution

DbSet implements both `IEnumerable` and `IEnumerable<T>,` so something like:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace efAW
{
    class Program
    {

        static IEnumerable GetAllMembers(DbContext db, string dbSetName)
        {
            var pi = db.GetType().GetProperty(dbSetName);
            return (IEnumerable)pi.GetValue(db);
        }
        static void Main(string[] args)
        {
            using (var db = new aw())
            {
                var customers = GetAllMembers(db, "Customers").OfType<Customer>().ToList();
            }
        }
    }
}

David

Problem

Let's say that I have ``` DBContext principal = new DBContext(); var x = principal.GetType().GetProperty("SomeClass").GetType(); ``` I now have the PropertyInfo of DbSet< SomeClass > What I'm trying to do now is somehow iterate (convert to list for example) and get the values from each row in the table. imagine I could do this: ``` x[0] // would be the 0th entery in DbSet<SomeClass>, the first row aka of type SomeClass ``` From here I would know how to further drill down and access properties (using the same principle as above)

Original source