Create Table, Run Time using entity framework Code-First

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

Accepted Answer

You certainly can.

Finding the Classes may help you with that:

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

Now that you've added some logic,OnModelCreating approach to yourcontext the ability to search assemblies and add any classes using the[Persist] as seen 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[] { });
      }
    }
  }
}

When new classes or attributes are introduced to the model, the database may be changed automatically by using the code-based data migration mechanism that is described below.

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

More information is available at Building A Model Dynamically Using Code First.

Update: How Can I Run a Dynamic Table Query?

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 : Using Entity Framework to query data from a table that was generated dynamically

4
5/23/2017 10:31:09 AM

Popular Answer

Finally, a query on a database context without any DbSets...

applying this

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

If the type and name of your design courses are almost identical to the corresponding Tables name on database, everything will operate as it should. (it has to be)

unique thanks to @Sampath



Related Questions





Related

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