简体   繁体   English

使用实体框架Code-First创建表,运行时

[英]Create Table, Run Time using entity framework Code-First

Is that possible to create table in run time by using EF Code-first? 是否可以通过使用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. 我可以使用C#CodeDOM(反射)在运行时创建我的模型类,但我无法在运行时设置我的Dbcontext类的dbSet属性。 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 . 什么是在运行时动态创建表的最佳解决方案?...有些人对我说,唯一的方法是使用经典的ADO.Net

Yes,you can do that. 是的,你可以这么做。

You can do that using Finding the Classes : 您可以使用查找类来执行此操作:

[AttributeUsage(AttributeTargets.Class)]
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. 现在,您可以向contextOnModelCreating方法添加一些逻辑,以扫描程序集并添加具有[Persist]属性的任何类,如下所示。

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 您可以阅读更多相关信息: 使用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 有关更多信息,请参阅此内容: 使用动态创建的表中的Entity Framework查询数据

finally to have a query on a dbContext which doesn't have any DbSet<>... 最后对dbContext进行查询,该查询没有任何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 @Sampath的特殊Tnx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM