Create a DbSet<T> dynamically in Entity Framework?

DbContext has method for this:

  var set = context.Set<MyEntity>();

Use:

DbSet<MyEntity> set = context.Set<MyEntity>();

Or, if you can't use the generic method:

DbSet set = context.Set(
    typeof( MyEntity )
);

Don't worry about second-loading and duplicating a POCO. Sets are cached internally by the Context.


This is my aproach:

    public static List<T> GetCollection<T>()
    {
        List<T> lstDynamic = null;

        using (MyDbContext db = new MyDbContext())
        {
            DbSet mySet = db.Set(typeof(T));
            mySet.Load();
            var list = mySet.Local.Cast<T>();

            lstDynamic = list.ToList();
        }
        return lstDynamic;
     }

And you call this function as:

List<Customer> lst = StaticClass.GetCollection<Customer>();

This returns your entire collection. I used this to perform a cache functionality for basic tables which don't change its content very often.