使用实体框架代码首先创建表,运行时间 [英] Create Table, Run Time using entity framework Code-First

查看:290
本文介绍了使用实体框架代码首先创建表,运行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是可能使用的 EF 代码先创建运行时表?
我可以使用C#的CodeDOM(反射)创建我的模型在运行时类,但我不能将 dbSet 我的的DbContext 在运行时类的属性。
什么你的想法?
最新最好的解决方案,在运行时动态创建的表?...
那些部分我,唯一的办法是使用经典的 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.

推荐答案

是的,你可以做到这一点。

Yes,you can do that.

您可以做在使用找到类:

You can do that using Finding the Classes :

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

现在,你可以将某些逻辑添加到你的上下文OnModelCreating 扫描组件,并添加任何类 [坚持] 。属性如下图所示。

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();

您可以阅读更多关于这一点:的 动态构建模型用的Code First

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

这篇关于使用实体框架代码首先创建表,运行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆