Create Table, Run Time using entity framework Code-First

c# ef-code-first ef-migrations entity-framework entity-framework-6


Is that possible to create table in run time by using EF Code-first? i could create my models class in run time by using C# CodeDOM(reflection) but i couldn't set the dbSet properties of my Dbcontext class in run time. whats your idea? whats the best solution to create table dynamically in run time?... some ones said to my that the only way is using classic ADO.Net.

10/1/2016 1:18:56 PM

Accepted Answer

Yes,you can do that.

You can do that using Finding the Classes :

public class PersistentAttribute : Attribute

Now you can add some logic to the OnModelCreating method of your context to scan assemblies and add any classes with the [Persist] attribute as shown below.

public class MyContext : DbContext
  protected override void OnModelCreating(DbModelBuilder modelBuilder)
    var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");

    foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
      var entityTypes = assembly
        .Where(t =>
          t.GetCustomAttributes(typeof(PersistentAttribute), inherit: true)

      foreach (var type in entityTypes)
          .Invoke(modelBuilder, new object[] { });

You can use below mentioned code based data migration method hence automatically change the database when new classes or properties are added to the model.

var config = new DbMigrationsConfiguration<MyContext> { AutomaticMigrationsEnabled = true };
var migrator = new DbMigrator(config);

You can read more about this : Dynamically Building A Model With Code First

Update : How to Query a Dynamic Table ?

public IEnumerable<ResultTableTemplate> GetResultsFromTable(string tableName) {
    using (var context = new MyContext()) {
        var query = context.ExecuteStoreQuery<ResultTableTemplate>("SELECT " +
            "ALL_THOSE_COLUMN_NAMES... " +
            "FROM " + tableName;

        return query.ToList();

See this for more : Querying data using Entity Framework from dynamically created table

5/23/2017 10:31:09 AM

Popular Answer

finally to have a query on a dbContext which doesn't have any DbSet<>...

using this:

var x = Db.Set<YourModelType>().ToList();

it's perfectly working if type and name of your model classes be much as like their related Tables name on database.(it has to be)

special Tnx for @Sampath

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow