Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>(); 
like image 707
skjagini Avatar asked Mar 15 '11 06:03

skjagini


People also ask

What is difference between DbSet and DbContext?

Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database. So it makes perfect sense that you will get a combination of both!

What is DbSet in Entity Framework?

A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext. Set method.

How does DbContext change state of entity?

This can be achieved in several ways: setting the EntityState for the entity explicitly; using the DbContext. Update method (which is new in EF Core); using the DbContext. Attach method and then "walking the object graph" to set the state of individual properties within the graph explicitly.

What is DbContext EF?

DbContext is a combination of the Unit Of Work and Repository patterns. DbContext in EF Core allows us to perform following tasks: Manage database connection. Configure model & relationship. Querying database.


1 Answers

DbContext has method for this:

  var set = context.Set<MyEntity>(); 
like image 111
Ladislav Mrnka Avatar answered Sep 23 '22 12:09

Ladislav Mrnka