Creating a table, runtime using the Code-First entity structure

Is it possible to create a table at runtime using EF Code-first? I could create a class of models at runtime using C # CodeDOM (reflection), but I could not set the dbSet properties of my Dbcontext class at runtime. what is your idea? What is the best solution for dynamically creating a table at runtime? ... some have told me that the only way is to use classic ADO.Net .

+5
source share
2 answers

Yes you can do it.

You can do this using Class Search:

[AttributeUsage(AttributeTargets.Class)] public class PersistentAttribute : Attribute { } 

Now you can add some logic to the OnModelCreating method of your context to test 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 .GetTypes() .Where(t => t.GetCustomAttributes(typeof(PersistentAttribute), inherit: true) .Any()); foreach (var type in entityTypes) { entityMethod.MakeGenericMethod(type) .Invoke(modelBuilder, new object[] { }); } } } } 

You can use the code-based data transfer method below, therefore, 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); migrator.Update(); 

You can learn more about this: Dynamically building a model with first code

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 the Entity Framework from a dynamically created table

+3
source

finally, to receive a request for dbContext, which has neither DbSet <> ...

using this:

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

it works fine if the type and name of your model classes are similar to their related Tables in the database . (he should be)

special Tnx for @Sampath

+2
source

Source: https://habr.com/ru/post/1257582/


All Articles