Create a DbSet<T> dynamically in Entity Framework?
-
24-10-2019 - |
Question
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>();
Solution
DbContext
has method for this:
var set = context.Set<MyEntity>();
OTHER TIPS
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow