EF6迁移自动迁移未执行

时间:2020-06-18 09:36:43

标签: c# sql-server entity-framework-6

嗨,我正在尝试采用EF6代码优先方法。我了解迁移的基本概念以及“代码优先”的工作原理,但是以某种方式却无法工作。我本人不是通过Add-Migration编写了以下Migration类:

public override void Up()
{
  CreateTable("dbo.Todo", column => new 
  {
    Id = column.Int(nullable:false, identity:true),
    Value = column.String(nullable: true),
    CreatedAt = column.DateTime(nullable: false, defaultValueSql: "GETUTCDATE()")
  }).PrimaryKey(t => t.Id);
}

public override void Down()
{
  DropTable("dbo.Todo");
}

但是up方法不称为“我的配置”类如下:

internal sealed class Configuration : DbMigrationsConfiguration<DataProviderCodeFirst.Entities.TodoContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = false;
        ContextKey = nameof(TodoContext);
    }

    protected override void Seed(DataProviderCodeFirst.Entities.TodoContext context)
    {
    }
}

这是我的DataContext:

public TodoContext(): base("SomeConnectionString")
{

}

public TodoContext(string connectionString)
  : base(connectionString)
{
  Database.CreateIfNotExists();
  Database.SetInitializer(new MigrateDatabaseToLatestVersion<TodoContext, Configuration>());
  Database.Initialize(false);
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  base.OnModelCreating(modelBuilder);
  modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}


public virtual DbSet<Todo> Todos { get; set; }

我的实体类

  public class Todo
  {


    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime CreatedAt { get; set; } = DateTime.Now;

    public string Value { get; set; }

  }

它将创建数据库和将键设置为标识的表,但未将CreatedAt设置为计算值,并且在调试Up()函数时未调用它。

谢谢前进

1 个答案:

答案 0 :(得分:0)

您必须先运行“启用迁移”,然后运行“添加迁移”命令,然后运行“更新数据库”命令。