首先生成 table 代码,而不是在应用程序 运行 上生成 table

generating table code first not generating table on application run

我有一个网站。首先使用COde。我的添加迁移命令生成了以下代码。

public partial class StudentEntity : DbMigration
{
    public override void Up()
    {



        CreateTable(
            "dbo.Student",
            c => new
                {
                    id = c.Int( nullable: false, identity: true),
                    name = c.String(),
                })
            .PrimaryKey(t => t.id);


    }

现在我想部署我的站点,所以当站点 运行 第一次我希望学生 table 在数据库(SQL 服务器)中生成时。

现在,当我 运行 网站时,它不会创建任何 table。我怎样才能做到这一点?我不想用

初始化任何种子数据

我的数据库上下文 class

  public partial class flagen:DbContext
{
    public flagen() : base("name=cf2")
    {
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
    //old entity
    public virtual DbSet<flag> flags { get; set; }
    //new entity
     public virtual DbSet<Student> students { get; set; }
}

然后我尝试使用上下文来创建 table。它抛出错误 "The model backing the 'flagen' context has changed since the database was created. Consider using Code First Migrations to update the database " 我在 dbcontext class

中添加了以下两行
  Database.SetInitializer<flagen>(null);
        base.OnModelCreating(modelBuilder);

现在显示 "invalid object name students"

任何有效的解决方案?

一个解决方案可能是定义一个初始化程序,它将您的数据库迁移到您添加的最后一个现有迁移。因此,所有表都将被创建,配置的 Seed 方法也将被执行——您可以使用它来播种数据。 在以下示例中,您的数据库将在数据上下文首次初始化时更新为上次现有迁移(并因此创建所有表)。 (var dbContext = new MyDatabaseContext()) 在我看来,这是一种比使用 AutomaticMigrationsEnabled = true 更简洁的方法,您也可以查看。 ;)

此处提到的示例将使用具有定义行为的 MigrateDatabaseToLatestVersion 初始值设定项。

public partial class MyDatabaseContext : DbContext
{
    public virtual DbSet<Student> students { get; set; }



    public MyDatabaseContext() : base("MyDatabaseContextConnectionString")
    {
        System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDatabaseContext, Migrations.Configuration>());
    }



    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // here we want to define the entities structure
    }    
}

您将找到有关初始化程序本身的更多信息hereMSDN - MigrateDatabaseToLatestVersion) and here (Entity Framework Tutorial - Code-First Tutorials - Automated Migration) 是另一个包含更多背景信息和示例的示例.

本题答案是使用T4模板。在网上搜索后,我得到了没有人可以这样的答案。耻辱...

https://archive.codeplex.com/?p=t4dacfx2tsql