30

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>();
DavidRR
  • 18,291
  • 25
  • 109
  • 191
skjagini
  • 3,142
  • 5
  • 34
  • 63

3 Answers3

48

DbContext has method for this:

  var set = context.Set<MyEntity>();
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • I have used something similar in my project but i encountered a small problem. The DbSet iscreated dynamically and the in-memory graph works nicely; However, when the time comes to store the data into the database e.g. context.SaveChanges() the following exception is throws: Invalid object name 'dbo.CustomModel'. – ppoliani Sep 23 '13 at 09:55
  • Looks like some problem with your mapping because it tries to access db object which doesn't exist – Ladislav Mrnka Sep 25 '13 at 15:28
21

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.

DavidRR
  • 18,291
  • 25
  • 109
  • 191
Jan 'splite' K.
  • 1,667
  • 2
  • 27
  • 34
2

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.

jaimenino
  • 64
  • 3