创建表,运行时使用实体框架代码优先

创建表,运行时使用实体框架代码优先

问题描述:

可以通过使用 EF 代码优先在运行时创建表吗?
我可以使用C#CodeDOM(反射)在运行时创建我的模型类,但是我无法在运行时设置我的 Dbcontext 类的 dbSet 属性。
你的想法是什么?
什么是在运行时动态创建表的最佳解决方案?
有些人对我说,唯一的方法是使用经典的 ADO.Net

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.

是的,你可以这样做。

使用查找类:

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

现在,您可以添加一些逻辑到 OnModelCreating 您的上下文的方法来扫描程序集并添加任何类与 [Persist] 属性如下所示。

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
        .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 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);
migrator.Update();

您可以阅读更多关于这一点: 使用代码优先动态构建模型

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

更新:如何查询动态表?

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