【问题标题】:generating table code first not generating table on application run生成表代码首先不在应用程序运行时生成表
【发布时间】:2017-11-30 09:47:52
【问题描述】:

我有一个网站。首先使用代码。我的 add-migration 命令产生了以下代码。

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


    }

现在我想部署我的站点,所以当站点第一次运行时,我希望在 DB(SQL 服务器)中生成 Student 表。

现在,当我运行该站点时,它不会创建任何表。我怎样才能做到这一点?我不想用任何种子数据初始化

我的数据库上下文类

  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; }
}

然后我尝试使用 Context 来创建表。它抛出错误“支持'flagen'上下文的模型自数据库创建以来已更改。考虑使用代码优先迁移来更新数据库” 我在 dbcontext 类中添加了以下两行

  Database.SetInitializer<flagen>(null);
        base.OnModelCreating(modelBuilder);

现在它显示“无效的对象名称学生”

任何有效的解决方案?

【问题讨论】:

  • EF 在站点启动时不会初始化,它会在您第一次尝试使用上下文时运行。你试过这样做吗?
  • @DavidG 当我第一次尝试使用上下文时,它给了我以下错误:“支持'flagen'上下文的模型自数据库创建以来发生了变化。考虑使用代码优先迁移来更新数据库( go.microsoft.com/fwlink/?LinkId=238269)。”
  • 现在这是一个不同的问题......
  • @DavidG 更新问题
  • 现在我们有第三个不同的问题。你不能一直这样改变你的问题。

标签: c# entity-framework ef-code-first


【解决方案1】:

一种解决方案可能是定义一个初始化程序,它将您的数据库迁移到您添加的最后一个现有迁移。因此,所有表都将被创建,并且配置的 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
    }    
}

你会发现更多关于初始化器本身的信息here (MSDN - MigrateDatabaseToLatestVersion)和hereEntity Framework Tutorial - Code-First Tutorials - Automated Migration)是另一个包含更多背景信息和示例的示例。

【讨论】:

    【解决方案2】:

    这个问题的答案是使用 T4 模板。在网上搜索后,我得到了没有人能在 SO 上的答案。惭愧……

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

    【讨论】:

      猜你喜欢
      • 2017-05-20
      • 1970-01-01
      • 2012-09-07
      • 2014-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      • 1970-01-01
      相关资源
      最近更新 更多