skjagini
skjagini

Reputation: 3217

Create a DbSet<T> dynamically in Entity Framework?

In LINQ to SQL, I can create a repository dynamically using DataContext.GetTable<T>. Is there a similar way to do this in Entity Framework 4 other than declaring the properties on the specific DbContext? For example:

public MyDbContext: DbContext
{
    public DbSet<MySet> MySets {get; set;}
}

I would like to know how can I create/get a reference to MySets dynamically as I can with LINQ to SQL as in:

var mySet = MyDbContext.GetTable<MySet>();

Upvotes: 31

Views: 45713

Answers (3)

jaimenino
jaimenino

Reputation: 64

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.

Upvotes: 2

Jan &#39;splite&#39; K.
Jan &#39;splite&#39; K.

Reputation: 2114

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.

Upvotes: 21

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364389

DbContext has method for this:

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

Upvotes: 48

Related Questions