Automatic Migration and manual invocation of Update-Database

1.3k Views Asked by At

Do I have to manually issue the Update-Database command in the package manager console even though I have automatic migrations turned on?

I'm running MVC4 and EF6. The solution is targeted for .NET 4 (I can't change this unfortunately).

EDIT: I'm aware of the difference between Code Migrations that would require me to properly seed existing tables. This question is more based towards a scenario where I add a table that has no relations, which I would think would just run?

EDIT 2: Table that should be added automatically

============

New Table definition

public class InboundFile : Entity
{
    [Required]
    public String FilePath { get; set; }
}

EF Config file

    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = true;
        MigrationsDirectory = @"Migrations";
    }

    protected override void Seed(Unifi.Context.DBContext context)
    {
        context.InboundFiles.AddOrUpdate(
            x => x.FilePath,
            new InboundFile { CreateDate = DateTime.Now, ModifiedDate = DateTime.Now, FilePath = "c:/test", IsDeleted = false }
        );
    }

DB Context

public class DBContext : DbContext {

    public DBContext()
        : base("MyConn")
    {

    }

    public DbSet<User> Users { get; set; }

    public DbSet<UserRole> UserRoles { get; set; }

    public DbSet<Region> Regions { get; set; }

    public DbSet<InboundFile> InboundFiles { get; set; }

}
2

There are 2 best solutions below

0
On BEST ANSWER

Try placing this in your Application_Start

Database.SetInitializer(new MigrateDatabaseToLatestVersion<DbContext, Configuration>);
using (var temp = new DbContext()) {
    temp.Database.Initialize(true);
}

This will force it to run update-database, and in doing so seed, every time your application starts.

5
On

Update-Database triggers an "update" operation. You can run your app and database will be updated on app start.

I prefer to run Update-Database manually because I can see if there are any db migration errors.